Created
January 19, 2016 15:38
-
-
Save JanPetterMG/acb8a3fd5b4f1cf006aa to your computer and use it in GitHub Desktop.
Convert various relative URLs to absolute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert various relative urls to absolute | |
* | |
* @author Jan-Petter Gundersen (europe.jpg@gmail.com) | |
* @param $url - url to convert | |
* @param $base - parent url | |
* @return string - absolute url | |
*/ | |
function url_absolute($url, $base) | |
{ | |
// already absolute | |
if (strpos($url, '://')) { | |
return $url; | |
} | |
// shorthand scheme | |
if (substr($url, 0, 2) == '//') { | |
return parse_url($base, PHP_URL_SCHEME) . ':' . $url; | |
} | |
// queries and anchors | |
if (substr($url, 0, 1) == '#' || substr($url, 0, 1) == '?') { | |
return $base . $url; | |
} | |
// just add domain | |
if (substr($url, 0, 1) == '/') { | |
return parse_url($base, PHP_URL_SCHEME) . '://' . parse_url($base, PHP_URL_HOST) . $url; | |
} | |
// add slash to domain if needed | |
if (stripos($base, '/', 9) === false) { | |
$base .= '/'; | |
} | |
// relative path | |
$base_rel = parse_url($base, PHP_URL_PATH); | |
$base_rel = substr($base_rel, 0, strrpos($base_rel, '/') + 1); | |
while (strpos($url, '../') !== false) { | |
$url = substr_replace($url, '', strpos($url, '../'), strlen('../')); | |
$base_rel = substr($base_rel, 0, strrpos($base_rel, '/')); | |
$base_rel = substr($base_rel, 0, strrpos($base_rel, '/') + 1); | |
} | |
if (substr($base_rel, 0, 1) != '/') { | |
$base_rel = '/' . $base_rel; | |
} | |
return parse_url($base, PHP_URL_SCHEME) . '://' . parse_url($base, PHP_URL_HOST) . $base_rel . $url; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment