使用crontab运行PHP脚本
我知道问题也是如此,但无论我查阅了多少教程,我都无法让我的使用crontab运行PHP脚本,php,cron,crontab,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 th
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
'd改为/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
用户。根据您的设置,执行cronjob的用户没有运行此文件的权限www-data
- 命令行上没有$\u Cookie。cookie由用户浏览器发送。由于cli不是浏览器,因此无法读取cookies值。虽然您可以访问users$\会话,但这是另一回事。请查看此处以了解更多详细信息
mkdir('/var/www/html/cron/testdir');
只是想看看是否可以访问该文件,并在dir中创建一个目录。如果无法访问,请创建一个新组并添加当前用户(使用查找)
ls -al
在/var/www/html/cron)中,将运行cronjob的用户添加到组中,然后使该组拥有要运行的文件。请看关于这个问题的公认答案:我在一段时间前就如何做到这一点发表了文章
对于$\u COOKIE问题,您必须找到另一个解决方案。例如,使用Redis或Memcached作为缓存服务,可通过联机和cli配置访问
考虑添加
1>> /dev/null 2>&1
在cronjob行的末尾,如果您不这样做并且让cron每分钟运行一次,您将得到大量日志文件
为了全面了解使用php和cli时可能遇到的陷阱,请务必提供文件的完整路径。我的问题刚刚被搁置,因为它“还不起作用”@RichardErickson在推荐您不熟悉的网站时要小心。请看。当您从命令行运行
/usr/bin/php-q/var/www/html/cron/index.php
时会发生什么情况?@Mat'sMug感谢您的更正。我删除了我的错误评论。戴夫,很抱歉给你发错了网站。我只是用cookies看看crontab是否正常工作。谢谢你的提示。我会实施,看看它们是否有效。不客气,如果我能进一步帮助你,请告诉我。这很有效。我使用的测试是错误的,这是因为我对$\u饼干的误解。谢谢你向我解释这个概念。对未来的双重关注