I created this function/procedure, which extracts a relative path from the absolute path the to server (to be used in front end code, like specifying the path to an image). The reason I created this, is I want my content management system to be ultimately portable. I want to avoid using absolute URI paths, starting with
http://, because sites are sometimes developed under different domain names.
This means I want my path to go from something like: "/home/www/user/sitename/directoryname/" to "/directoryname/" where /directoryname/ is the first directory in the root of the site itself.
My function works, but I wonder if it will be perfect in all situations. I think there will be some instances where it may not work, but I'm not sure. I just patched it for instances when the last directory in the DOCUMENT_ROOT will occur in the upper path.
Worth noting, is that on some server configurations, the DOCUMENT_ROOT does not match the filepath obtained with dirname(__FILE__). This presents an interesting problem and is why I can't just replace the first instance of DOCUMENT_ROOT in comparison to the dirname() of the config file to obtain the path. However, even when the DOCUMENT_ROOT is not the same as the dirname() of root directory, I've found that the last couple of directory names are always the same.
I'm trying to make this configuration ultimately portable, so that it can be placed literally anywhere on the web, on any server, or even any directory within a site, and automatically "know" where it is.
Anyway, here it is, if anyone is bored and wants to take a look:
PHP Code:
define ("ROOT", dirname(dirname(__FILE__)));
//define("BASE", "/root/directory")
if(!defined("BASE")) {
function base($path) {
$base = "";//default
$compare = $_SERVER["DOCUMENT_ROOT"];
if(substr($compare, -1) == "/") {
$compare = substr_replace($compare, "", -1); //because some servers have a / at the end and some don't
}
while(basename($path) != substr($compare, 0 - strlen(basename($path)))) {
//if basename exists at end of DOCUMENT_ROOT, doesn't continue
$oldpath = $path;
$anchor = "/".basename($path);
$base = $anchor.$base;
$path = dirname($path);
}
if(!empty($base) && substr_count($base, $anchor) !== substr_count($oldpath, $anchor) - substr_count($compare, $anchor))
{//recursive if needed (because last directory of DOCUMENT_ROOT might exist in the URI path)
$base = base($path);
}
return $base;
}
define ("BASE", base(ROOT));
}