include-paths in included file fail

独自空忆成欢 提交于 2019-12-02 00:42:28

问题


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:

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')

The content of the .inc.php-files is irrelevant here.

Here’s the problem:

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?

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

回答1:


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'

From the documentation:

__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 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]



来源:https://stackoverflow.com/questions/19067549/include-paths-in-included-file-fail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!