包含文件中的include-paths失败

时间:2013-09-28 13:33:34

标签: php include include-path

我有一些PHP包含路径的麻烦,不明白,有什么不妥。 首先,我想向您展示我的文件/目录结构:

文件/目录结构

 |index.php
 |foo/
     |baz.php
     |bar.inc.php
 |asdf/
     |qwerty.inc.php

的index.php:

  include('foo/baz.php');

/foo/baz.php:

  include('bar.inc.php');
  include('../asdf/qwerty.inc.php')

.inc.php - 文件的内容与此无关。

问题在于:

如果我直接致电/foo/baz.php,这两项工作正常。但是如果我打电话给/index.php,那么第一个包括作品而第二个包括失败。那是为什么?

第一条路径明显转换为包含,但不是第二条路径。我发现,这与先前的../有关,但我不知道如何解决这个问题。这可能是PHP的安全/配置问题吗?

顺便说一句,错误输出是:

Warning: include(../asdf/qwery.inc.php): failed to open stream:
No such file or directory in /foo/baz.php

1 个答案:

答案 0 :(得分:4)

从运行脚本的位置评估包含。当您include另一个文件时,您实际上是将该文件的内容提取到该位置的运行脚本中。

对于应评估的文件包括相对于包含文件的位置,您可以这样做:

<强> /foo/baz.php

include(dirname(__FILE__) . '/bar.inc.php';
include(dirname(__FILE__) . '/../asdf/qwerty.inc.php'

来自文档:

__FILE__是文件的完整路径和文件名。如果在include中使用,则返回包含文件的名称。从PHP 4.0.2开始,__FILE__总是包含已解析符号链接的绝对路径,而在旧版本中,它在某些情况下包含相对路径。

dirname给定一个包含文件或目录路径的字符串,此函数将返回父目录的路径。

[http://php.net/manual/en/function.dirname.php] [http://php.net/manual/en/language.constants.predefined.php]