Determining the Installation Path of Your PHP Script
Posted on May 2, 2006
Filed Under /dev/null/ | 68 views |
Back in April Ben XO posted this incredibly handy chunk of PHP that figured out the installation path of the script that executes it, relative to the server’s root.
I like my code wrapped in classes and functions, and I reserve uppercase notation for constants so I’ve re-formatted it thusly:
function getInstallationPath()
{
$realScriptDir = realpath( dirname( $_SERVER['SCRIPT_FILENAME'] ) );
$realBaseDir = realpath( dirname(__FILE__) );
$myPathPart = substr( $realScriptDir, strlen( $realBaseDir ) );$installationPath = $myPathPart ? substr( dirname($_SERVER['SCRIPT_NAME']), 0, -strlen($myPathPart) ) : dirname($_SERVER['SCRIPT_NAME']);
return $installationPath;
}
However sometimes you just want to know the root installation directory of your project, say because your configuration file lives there. For that I wrote this function:
function getRootPath()
{
$pathArray = explode( “/”, $_SERVER['SCRIPT_NAME'] );
$rootPath = $_SERVER['DOCUMENT_ROOT'] . “/”;
if ( false == strpos( $pathArray[1], “.” ) )
{ $rootPath .= $pathArray[1] . “/”; }
return $rootPath;
}
Comments
Leave a Reply