简体   繁体   中英

PHP Include behaving strangely?

For some reason if i inlcude() a file deeper in the file structure to where the file calling the include() is, 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.

除了什么其他人说我realpath例如一切...:

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

尝试这个:

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

您也许应该尝试将其基于当前目录:

include(getcwd() . '../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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM