简体   繁体   English

Crontab和PHP require_once无法正常工作

[英]Crontab and PHP require_once not working well

So I have a cron tab set up 所以我设置了一个cron标签

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed
  40 14 *  *  * root php /home/sites/sitename/batch/sendemailtest.php

Now here is the problem, when I run php sendemailtest.php inside the batch directory, everything works fine. 现在这是问题所在,当我在批处理目录中运行php sendemailtest.php ,一切正常。 But if I run it from any other directory like php /home/sites/sitename/batch/sendemailtest.php it gives me trouble. 但是,如果我从任何其他目录(例如php /home/sites/sitename/batch/sendemailtest.php运行它,则会给我带来麻烦。

I think it's because inside that php file is a require_once : 我认为这是因为该php文件中是require_once

require_once '../includes/dbpw.php';

So I am guessing the location I call the php file messes everything up. 因此,我猜我称之为php文件的位置将所有内容弄乱了。

How do I fix this? 我该如何解决?

I haven't tried this yet, in fear it will have unintended results... but if I change HOME=/ to HOME=/home/sites/sitename/batch/ , then have it run php sendemailtest.php , would that work? 我还没有尝试过,担心会产生意想不到的结果...但是,如果我将HOME=/更改为HOME=/home/sites/sitename/batch/ ,然后让它运行php sendemailtest.php ,那行得通php sendemailtest.php

The cronjob is run from the home directory of the user that the crontab is associated with. cronjob从与crontab关联的用户的主目录中运行。 There are a couple of ways to get relative paths working correctly from a cronjob like this, but the easiest in my opinion is to just change directories before calling the script. 有两种方法可以使像这样的cronjob正确地运行相对路径,但是我认为最简单的方法是在调用脚本之前先更改目录。

40 14 * * * root cd /home/sites/sitename/batch && php sendemailtest.php

There are a few options: 有几种选择:

  1. Change the include call to be an absolute file. 将include调用更改为绝对文件。 include('/home/sites/sitename/batch/scriptname.php') . include('/home/sites/sitename/batch/scriptname.php')
  2. Use chdir in the top of the php file to change it's working directory. 使用php文件顶部的chdir更改其工作目录。 To php this will act as if the script was run from within that directory. 对于php,这就像脚本是从该目录中运行一样。 In php: chdir('/home/sites/sitename/batch') . 在php中: chdir('/home/sites/sitename/batch') All scripts after this call will appear as if run from the new working directory. 此调用之后的所有脚本都将显示为好像从新的工作目录运行。
  3. Change the directory in the command like Glen is suggesting. 像Glen所建议的那样在命令中更改目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM