运行 带有 crontab 的 PHP 脚本

Running a PHP script with crontab

我明白 SO 是为了问题,但无论我查阅了多少教程,我都无法让我的 crontab 工作,我正在建立一个将依赖 crontab 重置的网站每晚在我的数据库中进行特定设置。

这是我的 crontab 文件:

# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command
* * * * * /usr/bin/php -q  /var/www/html/cron/index.php

如果我尝试 cd/usr/bin/php 我得到

-bash: cd: /usr/bin/php: Not a directory

所以我 cd 只是 /usr/bin/ 这就是我发现的:

-rwxr-xr-x  1 root   root      27216 Feb 10 15:08 pgrep*
lrwxrwxrwx  1 root   root         21 Jun 13 09:36 php -> /etc/alternatives/php*
-rwxr-xr-x  1 root   root    9049256 Jul  2 11:57 php5*

如果我 cd/etc/alternatives 我发现:

lrwxrwxrwx  1 root root   13 Jun 13 09:36 php -> /usr/bin/php5*

我回到 bin 文件,php5* 符号并且是绿色的。

-rwxr-xr-x  1 root   root    9049256 Jul  2 11:57 php5*

我的 PHP 脚本。很简单的。检查 cookie,如果存在,则将其递增 1。然后我在另一页上检查结果。手动这个工作。使用 crontab,无法正常工作。

if (!empty($_COOKIE['cronTest'])) {
  $int = $_COOKIE['cronTest'];
  $int++;
  setcookie("cronTest", $int, time()+3600);
}
  • 很可能,您在 /var/www/html/cron 中的脚本归 www-data 用户所有。根据您的设置,执行 cronjob 的用户无权访问 运行 此文件。

  • 命令行上没有$_COOKIE。 cookie 由用户浏览器发送。由于 cli 不是浏览器,因此您无法读取 cookies 值。虽然您可以访问用户 $_SESSION,但那是另一回事了。在这里 Is it possible to read cookie/session value while executing PHP5 script through command prompt? 查看更多详细信息。

您的 cronjob 行看起来有效,因此问题将是以上几点之一。要验证第一个,请尝试在文件中不使用 $_COOKIE 的情况,例如

mkdir('/var/www/html/cron/testdir');

就是看文件能不能访问,在dir上面创建目录。如果不能访问,新建一个组,同时添加当前用户(用

查找
ls -al

in /var/www/html/cron ) 和用户 运行 将 cronjob 分配给该组,然后让该组拥有您想要 运行 的文件。请参阅关于此问题的已接受答案:Set user permissions | Artisan command will not run in code but works fine on command line 我之前发布了有关如何执行此操作的信息。

对于$_COOKIE 问题,您将不得不寻找其他解决方案。例如,使用 Redis 或 Memcached 作为可以通过在线和 cli 配置访问的缓存服务。

考虑添加

1>> /dev/null 2>&1

到你的 cronjob 行的末尾,如果你不这样做并让 cron 运行 每分钟这样,你将获得大量日志文件。

为了完善使用 php 和 cli 时可能出现的陷阱,请始终确保提供文件的完整路径。