php nested include behavior
In cases when I need to use relative paths I use the following syntax:
include (realpath(dirname(__FILE__)."/another_folder/myfile.php"));
I would recommend using absolute paths. A good way to do this while still being portable is to make a declaration like this in your public_html/index.php:
define('ROOT', dirname(__FILE__));
Then, you can write includes like this which are very easy:
include(ROOT.'/file.php');
Otherwise, PHP checks to see if the file is in the include path as defined by your php.ini. If it's not there, it tries a relative path to the current script. Which is unpredictable and unmaintainable since you may be nestingly including files from different relative locations.
Edit: If you're constantly including a lot of class files, you may want to look into autoloading. It makes everything way simpler if you're programming in an object-oriented style. I have personally never written the word 'include' in my code for a very long time.
Edit 2: You could use the php.ini directive auto_prepend_file
to automatically include a one-line file with the definition of ROOT to each one of your scripts.
As someone on the php learning curve, I have found the best way to reference include paths is by absolute location, not relative, by using the built-in $_SERVER
superglobal. In my own files I have been using this with success:
include $_SERVER [ 'DOCUMENT_ROOT' ] . '/path_from_root/file_name.php';
This way it doesn't matter where the included file resides relative to my calling file, and I don't have to worry about manually typing in my fully qualified server path. (Maybe obvious..) This will work no matter how nested the include call is, and if / when I move the calling file to a different directory, for example.
You can use this method with include
, require
, and any other file-related functions that need a path.
On a related note..
$_SERVER [ 'PHP_SELF' ]
will return the path (relative to the root) of the current file. I also use this quite a bit.
$_SERVER
has other useful info you may want to check out here:
http://php.net/manual/en/reserved.variables.server.php
Sorry if this is an older thread, I'm new here.
EDIT: You could save this 'DOCUMENT_ROOT'
to a variable for use later, but from recent experience I would recommend against it because then you have to worry about variable scope. The include line as written will work every time regardless of current scope.