Skip to content

Instantly share code, notes, and snippets.

@woodywang
Created June 18, 2011 12:46
Show Gist options
  • Save woodywang/1033062 to your computer and use it in GitHub Desktop.
Save woodywang/1033062 to your computer and use it in GitHub Desktop.
Convert a relative URL to absolute one, depends on the current base URL.
<?php
function convertRelativeToAbsolute($relativeUrl, $baseUrl)
{
preg_match('/^([\w\d]+?):\/\/([^\/]+)(\/[^\?#\.]+)?/', $baseUrl, $match);
$scheme = $match[1];
$host = $match[2];
$basePath = '/';
if(!empty($match[3]))
{
$basePath = $match[3];
}
$baseDir = substr($basePath, 0, strrpos($basePath, '/'));
if(strpos($relativeUrl, '?') !== false)
{
list($relativeUrl, $queryString) = explode('?', $relativeUrl);
}
$currentDirArr = explode('/', $baseDir);
$relativeUrlArr = explode('/', $relativeUrl);
foreach($relativeUrlArr as $dir)
{
if($dir == '..')
{
array_pop($currentDirArr);
}
else if($dir != '.')
{
$currentDirArr[] = $dir;
}
}
$absUrl = "$scheme://$host" . '/' . ltrim(implode('/', $currentDirArr), '/');
if(!empty($queryString))
{
$absUrl .= "?$queryString";
}
return $absUrl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment