PHP包含相对路径 [英] PHP include relative path
问题描述
我有/root/update/test.php文件.还有一个文件/root/connect.php;该文件有一行
I have file /root/update/test.php. There's also a file, /root/connect.php; This file has a line
include "../config.php";
在/root/update/test.php中.有代码
In /root/update/test.php. There's the code
set_include_path(".:/root");
include "connect.php";
当我运行/root/update/test.php时,它找到了connect.php,但是找不到config.php,给了我
When I run /root/update/test.php, it finds connect.php, but fails to find config.php, giving me
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).有人可以帮我清理一下吗?请注意,由于绝对路径已部署到我无权访问的生产服务器,因此我绝对不可以使用绝对路径.
This is confusing to me because the warnings make it seem like I'm doing everything correctly - the include path is /root, and it's looking for file ../config.php (/config.php), which exists. Can someone clear this up for me? Note that using absolute paths is not an option for me, due to deploying to a production server that I have no access to.
Ubuntu/Apache
Ubuntu/Apache
推荐答案
您始终可以使用__DIR__
将其包括在内:
You could always include it using __DIR__
:
include(dirname(__DIR__).'/config.php');
__DIR__
是"魔术常数",并返回当前文件的目录,不带斜杠.它实际上是绝对路径,您只需要将文件名连接到__DIR__
.在这种情况下,由于需要提升目录,我们使用PHP的dirname
提升文件树,然后从这里可以访问config.php
.
__DIR__
is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__
. In this case, as we need to ascend a directory we use PHP's dirname
which ascends the file tree, and from here we can access config.php
.
您也可以在此方法中设置根路径:
You could set the root path in this method too:
define('ROOT_PATH', dirname(__DIR__) . '/');
在test.php中
会将您的根目录设置为/root/
级别.
in test.php would set your root to be at the /root/
level.
include(ROOT_PATH.'config.php');
然后应从所需位置包含配置文件.
Should then work to include the config file from where you want.
这篇关于PHP包含相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!