开发者

PHP Include behaving strangely?

For some reason if i inlcude() a file deeper in the file structure to where the file calling the include() i开发者_开发技巧s, it works file, or if i include a file on the same level.

If i try to go include('../backFile.php') it tells me there was no file?

Any help :(


I'm not completely sure what you exact situation is. There is probably a simple fix to make that include work. That fix will probably be provided in another answer.

Instead, I'm going to offer you a best-practice (Well, maybe not 'best', but a good practice):

In the first file you call, or your configuration file, define a constant that is the path to the first directory your files are contained in.

So if you are working in /home/user/domains/test.com/:

DEFINE('SITE_PATH', '/home/user/domains/test.com/');

Then, whenever you include something, use that as a starting place

include(SITE_PATH . "lib/test.class.php");

This will make sure that PHP uses the full path to the file, and you don't have to worry about including the file relatively.

This is very helpful when you are changing files locations, as you don't have to change the includes when you move the file including everything.


In addition to what the others have said i realpath everything... for example:

include(realpath(dirname(__FILE__).'/../myFile.php'));


You should perhaps try basing it on the current directory:

include(getcwd() . '../backFile.php');


Try this:

include('./../backFile.php');


include depends on the php's include_path directive which is . by default (the directory where the current executing script is).

Use ini_set or set_include_path to set your own include_path.


When you specify a path (absolute or relative) in the parameter to include, it doesn't use the system include path, but instead resolves the path relative to the "main" file, which is usually an index.php of some sort.

For example, you've got three files, /www/index.php:

<?php
include('libs/init.php');

/www/test.php:

I was included!    

and /www/libs/init.php:

<?php
include('../test.php');

The include('../test.php') call will be resolved using the index.php's directory context, which is /www, so instead of /www/test.php you're actually trying to include /test.php.

To be honest, I have no idea why it works this way. My libs/init.php solves it like this:

define('DIR_ROOT', str_replace('\\', '/', dirname(dirname(__FILE__))));

And then prepend all paths with it. The str_replace call is to handle Windows paths more smoothly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜