您想要封装变化的内容,即请求的某个位置(从浏览器查看)到您网站的根 URL(再次从浏览器查看)的相对路径。
为此,您首先需要知道根 URL 和请求的 URL,在 PHP 中可能是这样的:
$rootURL = 'http://example.com/mysite/basedir/';
$requestURI = $_SERVER['REQUEST_URI']; # e.g. /mysite/basedir/subdir/index.php
然后 PHP 提供了多种字符串函数来将其转换为相对路径:
'../' + X
例如,您可以将其放入执行此操作的类中:
$relative = new RelativeRoot($rootURL, $requestURI);
echo $relative; # ../
echo $relative->getRelative('style/default.css'); # ../style/default.css
这样的类的一个例子是:
/**
* 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;
}
}