当包含include()的相对路径时,PHP检查哪些目录? [英] Which directories does PHP check when including a relative path with include()?
问题描述
这很奇怪,有没有人得出结论呢?
It's very odd,has anyone ever sum up with a conclusion yet?
有时它也会检查所包含文件的目录。
Sometimes it checks the directory of the included file,too.
但有时不会。
D:\ test\1.php
D:\test\1.php
<?php
include('sub\2.php');
D:\ test\2.php
D:\test\2.php
<?php
include('3.php');
其中 3.php
是相同的dir as 2.php
。
Where 3.php
is in the same dir as 2.php
.
以上是有效的,但为什么呢?当前目录应为 D:\ test
,但它仍然可以找到3.php,它位于 D:\ test\sub
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
更多故事(最终)
大约一年以前我遇到了这个问题,然后我最终修复了下面的硬编码:
About a year ago I met this problem,and then I ended up fixed it with the hardcoding like below:
Common.php:
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
推荐答案
如果你看一下您将在main / fopen_wrappers.c中找到php的源代码
If you take a look at the source code for php in main/fopen_wrappers.c you will find
/* check in calling scripts' current working directory as a fall back case
*/
if (zend_is_executing(TSRMLS_C)) {
char *exec_fname = zend_get_executed_filename(TSRMLS_C);
int exec_fname_length = strlen(exec_fname);
while ((--exec_fname_length >= 0) && !IS_SLASH(exec_fname[exec_fname_length]));
if (exec_fname && exec_fname[0] != '[' &&
exec_fname_length > 0 &&
exec_fname_length + 1 + filename_length + 1 < MAXPATHLEN) {
memcpy(trypath, exec_fname, exec_fname_length + 1);
memcpy(trypath+exec_fname_length + 1, filename, filename_length+1);
actual_path = trypath;
这似乎无条件执行,因此将始终使文件与包含/在同一路径中文件打开脚本可访问...作为include_path中指定的所有可能性之后的最后选择。并且只有在include()中没有定义相对路径或绝对路径时才会这样。
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()的相对路径时,PHP检查哪些目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!