drnpwmq4536 2013-03-22 22:38
浏览 16
已采纳

PHP include():用例来自原始脚本的PWD

When using PHP's include() and require() functions to include a file which in turn includes another file, the PWD (relative reference) for the second file's include() is the directory for the original script location (the first script in the stack as called by Apache), not for the current file. What is the design decision behind that, and what is the use-case?

For instance, suppose a generic database-connection class defined in ~/public_html/classes/database.php which stores its configuration data (usernames, passwords) out of the web root in ~/config.php. The author of the database configuration class would logically call the config file with the relative filename ../../config.php. However, this does not work as expected because the PWD is not of the database.php file but rather of the file which included it, which could be ~/public_html/index.php, ~/public_html/someDir/somePage.php or elsewhere.

I know to work around this by getting the directory of the current file with dirname(__FILE__). However, I cannot think of a single use case where I would want require() or include() to be relative to the original script location. What is the use case for it being as it is?

  • 写回答

2条回答 默认 最新

  • dqt66847 2013-03-22 22:47
    关注

    The function include() and require() handle relative path the same as any other file access function like fopen(), unlink() and mkdir().

    Path are always relative to PWD regardless of the location of the script.

    Take the following example into consideration:

    /home/foo/index.php does

    require_once('lib/maketest.php');
    

    /home/foo/lib/maketest.php does

    mkdir('test');
    

    This will create the directory /home/foo/test and not /home/foo/lib/test.


    I can image that this has chosen because a bash script that does mkdir test will also create the directory $PWD/test regardless of where the script is located.

    Having include() following the same logic as other file access functions makes sense. Consider the following code:

    if (file_exists('config.php')) include('config.php');
    

    If paths in include() would be relative to __DIR__ and paths in file_exists() to PWD the above code wouldn't work as expected.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 MATLAB中streamslice问题
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序