使用crontab运行PHP脚本

Dav*_*ave 3 php cron crontab

我理解这是问题,但不管我查了多少教程,我都无法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
Run Code Online (Sandbox Code Playgroud)

如果我试图cd/usr/bin/php我弄

-bash: cd: /usr/bin/php: Not a directory
Run Code Online (Sandbox Code Playgroud)

所以我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*
Run Code Online (Sandbox Code Playgroud)

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

lrwxrwxrwx  1 root root   13 Jun 13 09:36 php -> /usr/bin/php5*
Run Code Online (Sandbox Code Playgroud)

我回到bin文件,php5*符号,是绿色的.

-rwxr-xr-x  1 root   root    9049256 Jul  2 11:57 php5*
Run Code Online (Sandbox Code Playgroud)

我的PHP脚本.非常简单.检查cookie,如果存在,则将其递增1.然后我在另一页上查看结果.手动这是有效的.随着crontab,无法让它工作.

if (!empty($_COOKIE['cronTest'])) {
  $int = $_COOKIE['cronTest'];
  $int++;
  setcookie("cronTest", $int, time()+3600);
}
Run Code Online (Sandbox Code Playgroud)

chr*_*con 5

  • 最有可能的是,您的内部脚本/var/www/html/cronwww-data用户拥有.根据您的设置,执行cronjob的用户无权运行此文件.

  • 命令行中没有$ _COOKIE.用户浏览器发送cookie.由于cli不是浏览器,因此您无法读取cookie值.虽然你可以访问用户$ _SESSION,但这是另一个故事.看看这里是否可以通过命令提示符执行PHP5脚本时读取cookie /会话值?了解更多详情.

你的cronjob线看起来有效,所以问题将是以上几点之一.要验证第一个,请在您的文件中尝试不使用$ _COOKIE,就像简单一样

mkdir('/var/www/html/cron/testdir');
Run Code Online (Sandbox Code Playgroud)

只是为了查看是否可以访问该文件并在目录上创建一个目录.如果无法访问,请创建一个新组并添加当前用户(请查找

ls -al
Run Code Online (Sandbox Code Playgroud)

在/ var/www/html/cron中)和运行cronjob到组的用户,然后使该组拥有您要运行的文件.请参阅此问题的已接受答案:设置用户权限| Artisan命令不会在代码中运行,但在命令行上工作正常我在一段时间内回复了如何做到这一点.

对于$ _COOKIE问题,您必须找到另一种解决方案.例如,使用Redis或Memcached作为缓存服务,可以通过在线和cli配置访问.

考虑添加

1>> /dev/null 2>&1
Run Code Online (Sandbox Code Playgroud)

在你的cronjob行结束时,如果你不这样做并让cron每分钟运行一次,你将得到大量的日志文件.

为了完成使用php和cli时可能出现的陷阱,总是确保提供文件的完整路径.