php cron job没有运行

use*_*084 4 php linux cron crontab

root@xx:/var/www/test# which php
/usr/bin/php
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

这是我的test.php档案:

<?php
$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //implicitly creates file
Run Code Online (Sandbox Code Playgroud)

这是输出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
Run Code Online (Sandbox Code Playgroud)
root@xx:/var/www/test# php -v
PHP 5.4.34-0+deb7u1 (cli) (built: Oct 20 2014 08:50:30) 
Run Code Online (Sandbox Code Playgroud)

cron作业不会运行,问题出在php上.如果我手动运行该文件,一切正常.

php test.php
Run Code Online (Sandbox Code Playgroud)

相关问题:为什么crontab没有执行我的PHP脚本?.

fed*_*qui 9

您需要在脚本中使用完整路径.否则,cron将不知道该文件在哪里.

而不是

$my_file = 'file.txt';
Run Code Online (Sandbox Code Playgroud)

使用

$my_file = '/path/to/file.txt';
Run Code Online (Sandbox Code Playgroud)

可能你被file.txt收藏在某个地方/.

注意crontab在有限的环境中运行,因此它不能假设任何与路径有关的内容.这就是为什么你还必须提供完整的路径php,等等.

故障排除cron作业的常见问题:

使用相对路径.如果你的cron作业正在执行某种脚本,你必须确保在该脚本中只使用绝对路径.例如,如果您的脚本位于/path/to/script.php并且您尝试在同一目录中打开名为file.php的文件,则不能使用相对路径,例如fopen(file.php).必须从其绝对路径调用该文件,如下所示:fopen(/path/to/file.php).这是因为cron作业不一定从脚本所在的目录运行,因此必须专门调用所有路径.