I'm currently trying to use file_put_contents
to update a JSON file of mine. This is what my PHP currently looks like:
$result = file_put_contents('Resources/logs/file.json', $newJsonString);
if($result === true) {
echo "true";
} else {
echo "false";
}
However, it always returns false
. Nevertheless, I have set the directory permissions to 777 for BOTH Resources
and logs
. I have also set file permissions to 777 for file.json
.
The path is also correct, as file_get_contents
works with the same path from the same file.
To further prove my point, I have also ran sudo chown -R www-data:www-data /var/www/html/core/Resources/
to give permission to the directory Resources
(and everything within) to be written to by the user www-data
(which I'm assuming would allow the JSON file to be written to by running the PHP script online).
I don't know if this would be helpful, but I'm also running this PHP script by sending POST
data to it via JavaScript from a different server/website.
Why in the world is file_put_contents
STILL returning false and not writing to the file? It always makes the JSON file blank after it is ran.
Supplementary Code:
This is the whole chunk of code, including the file_put_contents
section:
$jsonString = file_get_contents('Resources/logs/file.json');
$data = json_decode($jsonString);
$data->coins = $data->coins + $coins;
$data->uses = $data->uses + 1;
print_r($data);
$newJsonString = json_encode($data);
$result = file_put_contents('Resources/logs/file.json', $newJsonString);
if($result === true) {
echo "true";
} else {
echo "false";
}
...and this is the JSON file:
{"coins":"0","uses":"0"}
Any help would be highly appreciated, I've been trying to fix this issue for one whole day already.
Edit 1:
I forgot to mention this, but this code was working perfectly fine yesterday for about an hour. Then all of a sudden it stopped working and started making the JSON file blank.
Edit 2:
I have just cleared the Apache error log, and the script it working again (which is good). However, file_put_contents
is still returning false
. What is going on...
Edit 3:
Thanks to Laurent Wartel I have updated my if statement for file_put_contents
and it seems like it is no longer returning false.
if($result === false) {
echo "Error";
} else {
echo "All good, $result bytes written";
}
Try to write a string to your file. This way you can determine if your problem resides on the file writing or the content generation:
file_put_contents('Resources/logs/file.json', 'Hello, file');
Also, I'd add a LOCK_EX flag to the file write call to make sure you are not running into concurrency issues.