Which directories does PHP check when including a

2019-04-06 11:04发布

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

3条回答
放我归山
2楼-- · 2019-04-06 11:46

Sometimes directory of the included file being current working directory and sometimes not
Current directory can be checked with getcwd()

查看更多
Emotional °昔
3楼-- · 2019-04-06 11:55

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;

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().

查看更多
我想做一个坏孩纸
4楼-- · 2019-04-06 11:57

It checks in the current path, and the directories listed in include_path.

You can run a phpinfo() to see your include path.

查看更多
登录 后发表回答