【问题标题】:Execute PHP in cron job on centos在centos上的cron作业中执行PHP
【发布时间】:2018-02-14 15:18:25
【问题描述】:

我的 cronjob 实验需要帮助,但我无法完成我想要的。以下是我做的事情。

  1. /var/www/html/bob/test/index.php中创建一个php文件
  2. 将目录和文件的权限设置为可执行(0777)
  3. 指定一个 cronjob

我的index.php

<?php 
$myfile = fopen("testfile.txt", "w");  
?>

我对 crontab -e 的各种测试参数不起作用

*/1 * * * * root /usr/bin/php /var/www/html/bob/test/index.php
*/1 * * * * root /var/www/html/bob/test/index.php
*/1 * * * * root php -q /var/www/html/bob/test/index.php
*/1 * * * * root /var/www/html/bob/test/index.php

查看我的一些 /var/log/cron 我没有看到任何错误指示。

Sep 6 15:55:01 localhost CROND[4866]: (root) CMD (root /var/www/html/bob/test/index.php)
Sep 6 15:56:01 localhost CROND[4872]: (root) CMD (root /var/www/html/bob/test/index.php)
Sep 6 15:57:01 localhost CROND[4878]: (root) CMD (root /var/www/html/bob/test/index.php)

最后,当我通过#php /var/www/html/bob/test/index.php 运行我的 php 时,代码执行良好并创建了该文本文件。

【问题讨论】:

  • 你检查过php错误日志吗?
  • 尝试使用文件 testfile.txt 的绝对路径,例如:$myfile = fopen("/home/xxxx/testfile.txt", "w");

标签: php cron centos


【解决方案1】:

您需要从您的 cronjob 中删除 root。日志显示它正在尝试以 /var/www/html/bob/test/index.php 作为参数执行名为 root 的程序。

改为使用以下内容作为您的 cronjob:

*/1 * * * * /usr/bin/php /var/www/html/bob/test/index.php

This answer 声明如果要设置用户以运行 cronjob,则必须直接编辑 /etc/crontab,而不是使用 crontab -e

【讨论】:

  • 感谢您的宝贵时间,仅删除 root 似乎并没有解决问题,但结合 @abderrahime 评论,包括绝对路径并删除 root 确实有效。
  • 没问题,很高兴你把它整理好了 :)
【解决方案2】:
1 * * * * /usr/bin/php /var/www/html/bob/test/index.php

如果这不起作用,那么您有权限问题,请尝试使用 chown 和 chmod 来授予正确的权限

对于 $myfile = fopen("testfile.txt", "w");尝试使用文件 testfile.txt 的绝对路径,例如:

 $myfile = fopen("/home/xxxx/testfile.txt", "w"); 

【讨论】:

  • 它必须是评论,而不是答案
猜你喜欢
  • 1970-01-01
  • 2014-04-04
  • 2012-01-14
  • 2014-04-16
  • 2011-12-15
  • 2012-03-04
  • 2013-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多