Writing a file in PHP with a cron

cron, php, plesk

Solution

What if you use `dirname(__FILE__)` (see) to get an absolute path to your "fileDirectory" directory ?

Something like this in your script, I guess, if your `fileDirectory` is a child of the directory where your file resides :

file_put_contents(dirname(__FILE__) . '/fileDirectory/' . $fileName, $fileContents);

That way, you don't depend on relative path, which can be wrong if your script is not launched from the "right" directory.

Problem

I am trying to write a file to a sub folder of the directory my cron script is in using file_ put_ contents. However, I keep getting a warning "failed to open stream: No such file or directory." I have this directory structure: httpdocs/scripts/fileDirectory The cron script lives in the scripts folder. I call it with the cron command: ``` php httpdocs/scripts/cron_writeFile.php ``` In the cron_writeFile file, I first tried: ``` file_put_contents('fileDirectory/', $fileName, $fileContents); ``` which works when I load the page in a browser, but not when the cron executes. When I require_once a file in a cron, I have to put the 'absolute' path to it: ``` require_once('httpdocs/scripts/requiredFile.php'); ``` So, I tried that: ``` file_put_contents('httpdocs/scripts/fileDirectory/', $fileName, $fileContents); ``` No luck. I'm pretty sure it's getting to the right folder because the warning is: "Warning: file_ put_ contents(httpdocs/scripts/fileDirectory/4.txt): failed to open stream: No such file or directory in /var/www/vhosts/myDomain.com/httpdocs/scripts/cron_writeFile.php on line 93" The both directories have write permissions. I am using a VPS running (I know it sucks and I need to upgrade, but I don't have the authority) Parallels Plesk Panel version 9.2.1 with PHP 5.0.4 The file does not exist and I need a new file each time the script runs. I am not sure if there is a certain way to define the file path or some other thing I am missing. Thanks for your help!

Original source