문제

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
도움이 되었습니까?

해결책

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]

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top