I want something that will work for calling an include from any file
that
lives n levels deep.
That's where you have to define a variable (or constant) that
tells the system where the web root is located, and then use that to
determine where you are in relation to that. For example:
<?php
function relate_path($me,$root = '/home/pilotpig/public_html') {
if(preg_match('/\/.*\.[a-z0-9]{2,5}$/Ui',$me)) { // If a file with
extension 2-5 alphanum chars
$me = dirname($me); // Strip the filename
// Then loop through the correct number of times.
for($i=0;$i<(substr_count($me,'/') -
substr_count($root,'/'));$i++) {
$me = dirname($me);
}
return $me; // Returns the resulting path.
}
return false; // If we were unable to get the path.
}
/*
Then use it as follows, presuming this file is
named /home/user/public_html/web/home.php
*/
if(($path = relate_path(__FILE__)) !== false) {
include($path.'/include/config.php');
} else {
// Handle the error for the incorrect inclusion attempt.
}
?>
Voila!
Also, what is the difference between a path that starts with "/",
versus the
same path but that does not have that leading "/", or that same path but
prefixed with "./"?
I.e., this:
/somepath/includes/file.php
.... is a true (absolute) path.
versus this:
somepath/includes/file.php
.... is a relative path from wherever the file is called.
versus this:
./somepath/includes/file.php
.... is a relative path from the CWD/PWD (Current Working
Directory/Present Working Directory).
P.S. - The function is untested, just rattled off from my brain
while I cook dinner, so if it doesn't work, at least you should get
the gist of where I'm going.... but try it anyway. ;-P