I'm trying to run a very simple PHP script on cron on a third-party hosting server and I have encountered a weird problem. The script's contents is NOT executed although I got confirmed that the cron does execute the script in sch开发者_如何学Ceduled times. I cannot check the Cron settings as it is not on my server, yet I would like to know if there is something I do wrong?
The script is for testing purpose only and thus it is very simple:
<?php
$file = fopen("file-" . rand(1000, 9999) . '.txt', 'w');
fwrite($file, 'cron');
fclose($file);
?>
When I run this script manually, the file is created. When I leave it on Cron, nothing happens. What can be the cause? The permissions of the script are 777. Do I do something wrong or is the problem on a server?
Many thanks.
Remember that a script running under cron has a very different environment than the same script being run manually on the command line. In particular, cron will have a different working directory than the shell prompt. You don't specify an absolute path for your file, so when the script is run by cron, it'll try to create that file in whatever directory is the CWD at that time. If the userid this job runs under doesn't have write permissions on that directory (or the file exists but owned by someone else), then the fopen will fail.
Never assume that a file operation succeeds. Always check for error conditions. And while you're at it, specify an absolute path for the file, so you KNOW where it will be written:
$filename = "/path/to/where/you/wantfile-" . rand(1000,9999) . '.txt';
$file = fopen($filename, 'w') or die("Unable to open $filename for output");
This probably because the script is run as some user other than apache. In some cases I will use curl and make the script check to see if the IP is the local IP to make sure it is being run from the right machine. There certainly less hackish ways to accomplish this, but this is always a quick and easy one.
精彩评论