I wanna make universal header/footer include files.
Universal here means to be applicable in files on any directory level without need to add “../” at any deeper level when
You want to encapsulate what varies, which is the relative path to some location of the request (viewed from the browser) to the root URL of your website (again viewed from the browser).
For that you first of all need to know the root URL and the URL of the request, in PHP this could be something like this:
$rootURL = 'http://example.com/mysite/basedir/';
$requestURI = $_SERVER['REQUEST_URI']; # e.g. /mysite/basedir/subdir/index.php
PHP then offers diverse string functions to turn this into the relative path:
'../' + X
For example you could put that into a class that does this:
$relative = new RelativeRoot($rootURL, $requestURI);
echo $relative; # ../
echo $relative->getRelative('style/default.css'); # ../style/default.css
An example of such a class would be:
/**
* Relative Path to Root based on root URL and request URI
*
* @author hakre
*/
class RelativeRoot
{
/**
* @var string
*/
private $relative;
/**
* @param string $rootURL
* @param string $requestURI
*/
public function __construct($rootURL, $requestURI)
{
$this->relative = $this->calculateRelative($rootURL, $requestURI);
}
/**
* @param string $link (optional) from root
* @return string
*/
public function getRelative($link = '')
{
return $this->relative . $link;
}
public function __toString()
{
return $this->relative;
}
/**
* calculate the relative URL path
*
* @param string $rootURL
* @param string $requestURI
*/
private function calculateRelative($rootURL, $requestURI)
{
$rootPath = parse_url($rootURL, PHP_URL_PATH);
$requestPath = parse_url($requestURI, PHP_URL_PATH);
if ($rootPath === substr($requestPath, 0, $rootPathLen = strlen($rootPath)))
{
$requestRelativePath = substr($requestPath, $rootPathLen);
$level = substr_count($requestRelativePath, '/');
$relative = str_repeat('../', $level);
# save the output some bytes if applicable
if (strlen($relative) > strlen($rootPath))
{
$relative = $rootPath;
}
}
else
{
$relative = $rootPath;
}
return $relative;
}
}