【问题标题】:Include relative file when run from cron从 cron 运行时包含相关文件
【发布时间】:2012-11-10 22:42:23
【问题描述】:

考虑一个简单的 PHP 脚本:

$ pwd
/var/www/site/public_html

$ cat a.php
#!/usr/bin/php -q
<?php
echo "a: ".getcwd();
require_once('b.php');
?>

$ cat b.php
<?php
echo "b: ".getcwd();
?>

$ ./a.php > output
$ cat output
a: /var/www/site/public_html
b: /var/www/site/public_html

然后我设置了一个简单的 cron 作业:

* * * * * /var/www/site/public_html/a.php > /var/www/site/public_html/output

但是,这是 cron 运行后的输出:

$ cat output
a: /home/user

路径已更改,require 函数无法再找到要包含的脚本。令人沮丧的是,我有另一台服务器,cron 作业确实保留了它的路径。我已经完成了配置选项,但无法弄清楚如何配置 PHP 以保持原始路径,即使作为 cron 作业运行也是如此。这是怎么做到的?

谢谢。

【问题讨论】:

    标签: php cron command-line-interface


    【解决方案1】:

    试试这个

    $fileRoot = dirname(__FILE__);
    require_once($fileRoot.DIRECTORY_SEPARATOR.'b.php'); 
    /* considering b.php is in same directory */
    

    【讨论】:

    • 这确实是最好、最便携的答案。
    【解决方案2】:

    在您的 cron 命令中,您可以将脚本设置为在指定的工作目录中运行:

    cd /var/www/site/public_html && ./a.php > output
    

    【讨论】:

    • 谢谢 MrCode。我将接受的答案移至 Waqar 的答案,因为他的答案确实解决了问题的根源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 2015-03-20
    • 2012-06-19
    • 2010-10-15
    • 1970-01-01
    相关资源
    最近更新 更多