开发者

Which directories does PHP check when including a relative path with include()?

开发者 https://www.devze.com 2022-12-22 16:30 出处:网络
It\'s very odd,has anyone ever sum up with a conclusion yet? Sometimes it checks the directory of the included file,too.

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/PH开发者_C百科P/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


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


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

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消