【问题标题】:PHP include incorrect search path taken?PHP包含不正确的搜索路径?
【发布时间】:2013-07-14 14:48:49
【问题描述】:

我在文件夹myfolder 中有一个文件test.php。 myfolder 还包含另一个名为 inner 的文件夹。

myfolder 和 inner 都包含一个名为 msg.php 的文件。整个布局如下所示:

  • 我的文件夹
    • test.php
    • 内
      • msg.php
    • msg.php

在test.php 中,我将include_path 设置为./inner 并包含文件msg.php:

<?php
error_reporting(E_ALL | E_STRICT);
ini_set("include_path", "./inner");
echo ini_get('include_path'); // shows ./inner
include("msg.php"); // outputs hello from myfolder/inner/msg.php
?>

但是,如果我将工作目录修改为./inner,则将包含myfolder/msg.php 而不是myfolder/inner/msg.php:

<?php
error_reporting(E_ALL | E_STRICT);
ini_set("include_path", "./inner");
echo ini_get('include_path'); // shows ./inner
chdir('./inner');
include("msg.php"); // outputs hello from myfolder/msg.php
?>

第二段代码不应该包括myfolder/inner/msg.php而不是myfolder/msg.php吗?

【问题讨论】:

  • 附注.. 当您执行 ini_set("include_path", "./inner"); 时,您会完全覆盖您的包含路径
  • @DevZer0,是的,我正在覆盖包含路径。因此,第二段代码应该包含 myfolder/inner/msg.php 而不是 myfolder/msg.php 对吧?
  • 在第二个示例中,您将 chdir 设置为 ./inner,然后告诉它将 include_path 设置为不存在的目录 ./inner。您实际上是在告诉它将包含目录设置为/inner/inner。尝试将包含目录设置为 /inner 而不是 ./inner
  • 是的,它应该包括./inner
  • @Pacerier:不,它首先检查脚本的调用目录。

标签: php include php-internals


【解决方案1】:

我们先来看看你的目录路径语法。

./inner

也就是说,在当前目录 (./) 中查找名为 inner 的目录。

不过,在将include_path 设置为./inner 之前,您将当前工作目录更改为./inner,所以现在您实际上是在寻找/myfolder/inner/inner/msg.php。

让我们再看看你的代码。

//Current working directory is /myfolder

//Here you change the current working directory to /myfolder/inner
chdir('./inner');

//Here you set the include_path to the directory inner in the current working directory, or /myfolder/inner/inner
ini_set("include_path", "./inner");

//You echo out the explicit value of include_path, which, of course, is ./inner
echo ini_get('include_path'); // shows ./inner

//include fails to find msg.php in /myfolder/inner/inner so it looks in the scripts directory, which is /myfolder/msg.php.
include("msg.php"); // outputs hello from myfolder/msg.php

检查documentation,其中说明了如果include() 找不到在提供的路径中引用的文件会发生什么:

include 最终会检入调用脚本自己的目录并 失败前的当前工作目录。

您应该尝试将 include_path 设置为 /myfolder/inner,或者,如果 /myfolder 实际上是您的根目录,那么您可以将其设置为 /inner。注意. 的省略,这意味着current working directory。仅使用/ 意味着查看根目录。

【讨论】:

    【解决方案2】:

    您的路径可能是错误的,请从路径中删除“./”。在我看来,你似乎是从我的文件夹中出来,然后寻找一个内在的东西。

    查看包含函数的文档:http://php.net/manual/en/function.include.php

    include 最终会在失败前检入调用脚本自己的目录和当前工作目录

    【讨论】:

    • 您的答案中的引用是为什么它在找不到/myfolder/inner/inner/msg.php 后仍然找到/myfolder/msg.php
    猜你喜欢
    • 1970-01-01
    • 2016-04-16
    • 2014-12-13
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    相关资源
    最近更新 更多