【问题标题】:Different behavior when PHP script executed through cron job通过 cron 作业执行 PHP 脚本时的不同行为
【发布时间】:2013-06-04 08:34:06
【问题描述】:

我有一个脚本,我们称它为 mainfile.php,其中包含同一目录中的文件。我将其包括如下:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once './myincludefile.php';
?>

如果我执行以下操作:

nohup php mainfile.php >/dev/null

它运行没有任何问题。但是,如果将其转换为 cron 作业,我会收到以下消息(在我的邮件假脱机中):

PHP Warning:  require_once(./myincludefile.php): failed to open stream: No such file or directory in /home/code/mainfile.php on line 5
PHP Fatal error:  require_once(): Failed opening required './myincludefile.php' (include_path='.:/usr/share/pear:/usr/share/php') in/home/code/mainfile.php on line 5

有什么想法吗?

【问题讨论】:

  • 通过 cron 运行任务时,您必须始终在脚本中指定完整路径。

标签: php cron nohup


【解决方案1】:

这是因为通过 cron 调用时脚本的当前工作目录不同。 (我假设它是/,根目录)

require_once 更改为:

require_once __DIR__ . '/myincludefile.php';

__DIR__ 将始终包含当前脚本所在的目录 - 而不是当前工作目录。这就是构建相对路径很方便的原因。

【讨论】:

    【解决方案2】:

    请将require_once './myincludefile.php';中的路径改为绝对路径

    然后运行这个命令

    nohup php-q mainfile.php >/dev/null
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-31
      • 2020-02-28
      • 1970-01-01
      • 2011-08-16
      • 2013-03-02
      • 2014-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多