包含文件中的包含路径失败 [英] include-paths in included file fail
问题描述
我在使用PHP包含路径时遇到了一些麻烦,并且不明白,那里出了什么问题. 首先,我想向您展示我的文件/目录结构:
I have some troubles with PHP include-paths and do not understand, what wrong there. First, I’d like to show you my file/dir structure:
|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
文件的内容与此处无关.
The content of the .inc.php
-files is irrelevant here.
如果我直接拨打/foo/baz.php
,则两个都可以正常工作.但是,如果我调用/index.php
,则第一个include起作用,第二个失败.为什么会这样?
If I call /foo/baz.php
directly, the two includes work fine. But if I call /index.php
, then the first include works and the second one fails. Why is that?
第一个路径显然在包含时转换,但是第二个路径却没有.我发现,这与前面的../
有关,但我不知道如何解决.这可能是PHP的安全性/配置问题吗?
The first path gets obviously converted on inclusion, but not so the second one. I figured out, that is has something to do with the preceeding ../
, but I don’t know how to work this out. Is this a safety/configuration issue of PHP perhaps?
顺便说一句,错误输出是:
By the way, error output is:
Warning: include(../asdf/qwery.inc.php): failed to open stream:
No such file or directory in /foo/baz.php
推荐答案
从运行脚本的位置评估包含内容. include
另一个文件时,实际上是在将该文件的内容拉入该位置的正在运行的脚本中.
The includes are evaluated from the location of the running script. When you include
another file, you are essentially pulling the contents of that file into the running script at that place.
对于应评估包含相对于所包含文件位置的文件,您可以执行以下操作:
For files that should evaluate includes relative to the included file's location, you can do this:
/foo/baz.php
include(dirname(__FILE__) . '/bar.inc.php';
include(dirname(__FILE__) . '/../asdf/qwerty.inc.php'
从文档中:
__FILE__
是文件的完整路径和文件名.如果在include中使用,则返回包含文件的名称.从PHP 4.0.2开始,__FILE__
始终包含已解析符号链接的绝对路径,而在旧版本中,在某些情况下,它包含相对路径.
__FILE__
is The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, __FILE__
always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
dirname
给定一个包含文件或目录路径的字符串,此函数将返回父目录的路径.
dirname
Given a string containing the path of a file or directory, this function will return the parent directory's path.
[http://php.net/manual/en/function.dirname.php] [http://php.net/manual/en/language.constants.predefined.php]
[http://php.net/manual/en/function.dirname.php] [http://php.net/manual/en/language.constants.predefined.php]
这篇关于包含文件中的包含路径失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!