PHPRO.ORG

PHP provides functions to get the webserver document root within the $_SERVER super global array, and for getting the current working directory with the getcwd() function. But it often occurs that the document is being served from another directory within the web tree. This function will get the current working directory, relative to the web server document root.


<?php

/**
 *
 * @get the current working directory, relative to the document root
 *
 * @return string
 *
 */
function getRelativeRoot()
{
    
/*** get the document root ***/    
    
$dr $_SERVER['DOCUMENT_ROOT'];

    
/*** get the current working directory ***/
    
$cwd getcwd();

    
/*** return the path ***/
    
return str_replace($dr'',  $cwd);
}

?>

Example Usage


<?php
    
/*** get the relative root path ***/
    
$relative_root getRelativeroot();

    echo 
$relative_root;
?>