root@xx:/var/www/test# which php /usr/bin/php
root@xx:/var/www/test# ls -la total 16 drwxrwxrwx 2 root root 4096 Nov 14 09:37 . drwxrwxrwx 6 root root 4096 Nov 13 15:51 .. -rwxrwxrwx 1 root root 153 Nov 14 09:35 test.php
这是我的test.php
文件:
<?php $my_file = 'file.txt'; $handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file
这是crontab -l
的输出:
#this is ok * * * * * touch /tmp/hello #this only creates an empty php_result.log * * * * * /usr/bin/php /var/www/test/test.php > /tmp/php_result.log
root@xx:/var/www/test# php -v PHP 5.4.34-0+deb7u1 (cli) (built: Oct 20 2014 08:50:30)
cron作业不会运行,问题在于php。 如果我手动运行该文件,一切运作良好。
php test.php
相关问题: 为什么crontab不能执行我的PHP脚本? 。
您需要在脚本中使用完整路径。 否则, cron
将不知道该文件在哪里。
所以而不是
$my_file = 'file.txt';
使用
$my_file = '/path/to/file.txt';
很可能你将file.txt
存储在/
某处。
注意crontab
在一个有限的环境中运行,所以它不能假设任何有关路径。 这就是为什么你也必须提供php
的完整路径等
解决与cron作业有关的常见问题 :
使用相对路径。 如果您的cron作业正在执行某种脚本,则必须确保在该脚本中只使用绝对路径。 例如,如果您的脚本位于/path/to/script.phpand中,您正试图在同一个目录中打开一个名为file.php的文件,则不能使用诸如fopen(file.php)之类的相对路径。 该文件必须从其绝对路径调用,如下所示:fopen(/path/to/file.php)。 这是因为cron作业不一定从脚本所在的目录运行,所以必须专门调用所有路径。