Search code examples
cronfopenfwrite

fwrite, fopen, and cronjob - not saving to proper location


I wrote a php script to get my latest Twitter tweet and save it to a file. Here is the part doing so :

// No errors exist. Write tweets to json/txt file.
$file = $twitteruser."-tweets.txt";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, json_encode($tweets));
fclose($fh);

This works fine when I run my php script directly in the browser, however, when I run the file from a cron job it creates the file in my user root directory (obviously not the correct place).

If I change the above line to :

$file = "public_html/get-tweets/".$twitteruser."-tweets.txt";

the cronjob now works and saves to the correct location, but then manually running the file in my browser gives an fopen error that the file does not exist.

What the heck is the problem? I need this to work both from cronjob and manually.


Solution

  • Use a full path from the root of the filesystem, then both should be fine.