【问题标题】:include-paths in included file fail包含文件中的包含路径失败
【发布时间】:2013-10-04 17:48:28
【问题描述】:

我在使用 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-files 的内容在这里无关紧要。

问题来了:

如果我直接拨打/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

【问题讨论】:

    标签: php include include-path


    【解决方案1】:

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

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

    /foo/baz.php

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

    来自文档:

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

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 2021-07-11
    • 2012-08-04
    • 2011-11-24
    • 2015-05-10
    • 2013-06-21
    相关资源
    最近更新 更多