gpt4 book ai didi

php - PHP包含相对路径

转载 作者:行者123 更新时间:2023-12-03 08:50:14 25 4
gpt4 key购买 nike

我有/root/update/test.php文件。还有一个文件/root/connect.php;该文件有一行

include "../config.php";

在/root/update/test.php中。有代码
set_include_path(".:/root");
include "connect.php";

当我运行/root/update/test.php时,它找到connect.php,但是找不到config.php,这给了我
PHP Warning:  include(../config.php): failed to open stream: No such file or directory in /root/connect.php on line 2
PHP Warning: include(): Failed opening '../config.php' for inclusion (include_path='.:/root')

这让我感到困惑,因为这些警告使我似乎似乎在正确地进行所有操作-包含路径为/root,并且它正在寻找存在的文件../config.php(/config.php)。有人可以帮我清理一下吗?请注意,由于部署到我无权访问的生产服务器,因此使用绝对路径不是我的选择。

Ubuntu/ Apache

最佳答案

您可以始终使用__DIR__包含它:

include(dirname(__DIR__).'/config.php');
__DIR__是一个“ magical constant”,它返回当前文件的目录,不带斜杠。它实际上是绝对路径,您只需要将文件名连接到 __DIR__即可。在这种情况下,由于需要提升目录,我们使用PHP的 dirname提升文件树,从这里我们可以访问 config.php

您也可以在此方法中设置根路径:
define('ROOT_PATH', dirname(__DIR__) . '/');

在test.php中,会将您的根设置为 /root/级别。
include(ROOT_PATH.'config.php');

然后应该可以从所需位置包含配置文件。

关于php - PHP包含相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43029138/

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