There is a Cron job on Ubuntu 16.04 which runs a PHP script
$parseinfo = 'parseme.json'; $handle = fopen($parseinfo, 'w'); fwrite($handle, json_encode($res));
to parse data into a JSON file. The PHP script is supposed to write data within the same folder where this PHP script is located in but I’ve faced a problem that JSON is being saved into root’s home directory:
This is how I set Cron job:
*/10 * * * * root /usr/bin/php /var/www/somederictory/somefolder/parse.php > /dev/null
ssh [email protected] cd /etc crontab -e :x
In short words: JSON is being saved into
/root while I want it to be saved into
What should I do to fix it?
Edit: It is not a duplicate, PHP works, JSON is being saved, but in a wrong way. And I’m asking to help me understand what’s wrong with current Cron settings.
Here is Solutions:
We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.
By default Cron jobs are executed in the user’s home directory. While in your script is not provided path where the output file to be saved, it will be saved into the directory where the script is executed.
According to the question, you want to generate the
.json file into the same directory where the script is located. So (in this case) you have to change your code in some way, similar as this:
$parseinfo = 'parseme.json'; $path = realpath(dirname(__FILE__)); $handle = fopen("$path/" . $parseinfo, 'w'); fwrite($handle, json_encode($res));
If you don’t want to change the script you could change the Cron job in this way:
*/10 * * * * root cd /var/www/somederictory/somefolder/ && php parse.php > /dev/null
Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂