当使用 include() 包含相对路径时,PHP 会检查哪些目录?
很奇怪,有人总结过结论吗?
有时它也会检查包含文件的目录。
但有时不是。
D:\test\1.php
<?php
include('sub\2.php');
D:\test\2.php
<?php
include('3.php');
其中 3.php
与 2.php
位于同一目录中。
上面的方法是有效的,但是为什么呢?当前目录应该是D:\test
,但它仍然可以找到3.php,它在D:\test\sub
<强>更多故事(最终)
大约一年前,我遇到了这个问题,然后我最终用如下的硬编码修复了它:
Common.php:
if (file_exists("../../../Common/PHP/Config.inc"))
include('../../../Common/PHP/Config.inc');
if (file_exists("../../Common/PHP/Config.inc"))
include('../../Common/PHP/Config.inc');
if (file_exists("../Common/PHP/Config.inc"))
include('../Common/PHP/Config.inc');
if (file_exists("Common/PHP/Config.inc"))
include('Common/PHP/Config.inc');
其中Config。 inc
与 Common.php 位于同一目录中
It's very odd,has anyone ever sum up with a conclusion yet?
Sometimes it checks the directory of the included file,too.
But sometimes not.
D:\test\1.php
<?php
include('sub\2.php');
D:\test\2.php
<?php
include('3.php');
Where 3.php
is in the same dir as 2.php
.
The above works,but why?The current directory should be D:\test
,but it can still find 3.php,which is in D:\test\sub
More story(final)
About a year ago I met this problem,and then I ended up fixed it with the hardcoding like below:
Common.php:
if (file_exists("../../../Common/PHP/Config.inc"))
include('../../../Common/PHP/Config.inc');
if (file_exists("../../Common/PHP/Config.inc"))
include('../../Common/PHP/Config.inc');
if (file_exists("../Common/PHP/Config.inc"))
include('../Common/PHP/Config.inc');
if (file_exists("Common/PHP/Config.inc"))
include('Common/PHP/Config.inc');
Where Config.inc
is in the same directory as Common.php
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您查看 main/fopen_wrappers.c 中 php 的源代码,您会发现
这似乎是无条件执行的,因此始终会在与包含/文件打开脚本可访问的路径相同的路径中创建一个文件... include_path 中指定的所有可能性之后的最后一个选择。并且仅当您未在 include() 中定义相对或绝对路径时。
If you take a look at the source code for php in main/fopen_wrappers.c you will find
This seems to be executed unconditionally and therefore will always make a file in the same path as the including/file-opening script accessible ...as the last choice after all possibilities specified in include_path. And only if you do not define a relative or absolute path in the include().
它检查当前路径以及 中列出的目录include_path。
您可以运行 phpinfo() 来查看包含路径。
It checks in the current path, and the directories listed in include_path.
You can run a
phpinfo()
to see your include path.有时包含文件的目录是
当前工作目录
,有时不是可以使用 getcwd() 检查当前目录
Sometimes directory of the included file being
current working directory
and sometimes notCurrent directory can be checked with
getcwd()