3

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

From terminal:

ssh root@example.com
cd /etc
crontab -e
:x

In short words: JSON is being saved into /root while I want it to be saved into /var/www/somederictory/somefolder/ 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.

galoget
  • 3,023
vNottbeck
  • 33
  • 4

1 Answers1

6

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
David Foerster
  • 36,890
  • 56
  • 97
  • 151
pa4080
  • 30,621