【问题标题】:PHP: How to deal with Cron script's include path?PHP:如何处理 Cron 脚本的包含路径?
【发布时间】:2019-04-22 02:06:47
【问题描述】:

我在我的虚拟主机的 CPanel 中设置了一个每分钟运行一次的 cron 脚本。 cron 运行正常,但我遇到了与脚本路径相关的问题,我不知道如何正确解决。我的大部分网站都使用 /home/mysite/public_html/ 作为根路径,但 cron 脚本使用 /home/mysite/ 作为根路径,没有 public_html 部分。

这会导致文件包含出现很多问题,因为我不得不在我的类加载器中通过检查默认路径和以 public_html/ 为前缀的替代路径来解决这个问题:

spl_autoload_register(function($class){
    $className = str_replace("\\", "/", $class);
    $classPath = "{$className}.php";
    $altClassPath = "public_html/{$classPath}";
    if(file_exists($classPath)) require $classPath;
    elseif(file_exists($altClassPath)) require $altClassPath;
    else throw new ClassNotFoundException("Fatal Error: Class {$class} either does not exist, or has its include path mis-configured!");
});

这感觉乏味且容易出错,我一点也不喜欢。有没有更好的方法来处理这个问题?我尝试在 cron 脚本上使用 set_include_path ,但它似乎对自动加载器也没有帮助。

【问题讨论】:

标签: php cron include-path


【解决方案1】:

一分钟前遇到了同样的问题。看起来很简单,但往往是最难得到的,因为每个人都知道,所以没有人大声说出来。

在我的情况下,使用所谓的 PHP 魔术常数解决了它。变量是:

__DIR__

并且它保存了它所使用的脚本的路径。无论是直接运行还是包含在其他一些 php 文件中。因此,您可以使用它来编写相对路径,该路径始终从文件所在的位置开始。像那个:

 include(__DIR__ . "/../somewhere/something.php");

Some more useful magic constants

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-23
    • 2012-08-28
    • 2011-12-22
    • 1970-01-01
    • 2014-11-08
    • 2011-02-15
    • 1970-01-01
    相关资源
    最近更新 更多