gpt4 book ai didi

PHP:需要路径不适用于 cron 作业?

转载 作者:IT王子 更新时间:2023-10-28 23:46:46 25 4
gpt4 key购买 nike

我有一个 cron 作业需要包含这个文件:

require '../includes/common.php';

但是,当它通过 cron 作业(而不是我的本地测试)运行时,相对路径不起作用。cron 作业运行以下文件(在实时服务器上):

/home/username123/public_html/cron/mycronjob.php

这是错误:

Fatal error: require(): Failed opening required '../includes/common.php' 
(include_path='.:/usr/lib/php:/usr/local/lib/php') in
/home/username123/public_html/cron/mycronjob.php on line 2

使用与 cron 作业相同的绝对格式,common.php 将位于

/home/username123/public_html/includes/common.php

这是否意味着我必须将第 2 行替换为:

require '/home/username123/public_html/includes/common.php';

?

谢谢!

最佳答案

在尊重所有当前答案的情况下,他们都采用了“更改 php 代码”的方法。

我不喜欢仅仅为了从 cron 运行它而更改我的 PHP 文件,因为它降低了代码的可移植性并增加了忘记更改一两个相对路径并破坏程序的机会.

改为在 cron 选项卡行更改目录,并保持所有相对路径和 PHP 文件不变。 例如

1 1 * * * cd /home/username/public_html/&& php -f script.php

检查 this answer

另请查看 this article ,我会引用相关部分

Depending on the code in your PHP script, it may only run correctly when called from a specific directory. For example, if the script uses relative paths to include files, it will only run if it is called from the correct directory. The following command shows how to call a PHP script from a specific directory:

cd /home/username/public_html/; php -q script.php

关于PHP:需要路径不适用于 cron 作业?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3118699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com