包含一个文件,其中包含文件在PHP [(!)警告] [重复]

Possible Duplicate:
PHP: Why such weird behaviour when I include a file from another directory which also includes a file?

I have a problem including a file that has an included file.

  • core.inc.php PATH: www/test/includes/core.inc.php

  • included file in core.inc.php : include_once ('../../connectdb.php');

  • connectdb.php PATH: www/connectdb.php

  • index.php PATH: www/test/index.php

  • included file in index.php : include_once ('included/core.inc.php');

When I run index.php the following warnings are popping up:

(!) Warning: include_once(../../connectdb.php): failed to open stream: No such file or directory in G:\wamp\www\test\includes\core.inc.php on line 7

(!) Warning: include_once(): Failed opening '../../connectdb.php' for inclusion (include_path='.;C:\php\pear') in G:\wamp\www\test\includes\core.inc.php on line 7

In order to dinamically change the included paths what is the best practice? Please help me on my problem. Thank you.

To avoid such problems, you may use PHP magic constant __DIR__ which will be replaced by current file's directory.

For example:

include_once(__DIR__ . '/relative/path/to/file-to-include.php'); 

Note that __DIR__ is only available for PHP 5.3+. Below that version you can replace __DIR__ by dirname(__FILE__)

BTW, autoloading is a good practice to avoid includes mess.

included file in index.php : include_once ('./includes/core.inc.php');

Your relative path in index.php pointing to the core.inc.php is simply wrong.

You are saying: "From the location of index.php, on directory up, and there it is." But there is no file "core.inc.php" in the "www" directory.

The correct path is "includes/core.inc.php": From the current directory "www/test" one directory up into "includes" and there it is.

Any mentions of using __DIR__ or __FILE__ magic constants will also work, but this is a different approach: It will create an absolute path to the file by using relative additions. It works the same, but looks more complicated.

If you are using classes, try to implement autoloading. Then you do not need to include files explicitly, you simply use the classes.