Created
July 15, 2014 09:33
-
-
Save arioch1984/3d68718be998d6934edc to your computer and use it in GitHub Desktop.
Relative to absolute path
This file contains hidden or 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
function make_absolute($url, $base) | |
{ | |
// Return base if no url | |
if( ! $url) return $base; | |
// Return if already absolute URL | |
if(parse_url($url, PHP_URL_SCHEME) != '') return $url; | |
// Urls only containing query or anchor | |
if($url[0] == '#' || $url[0] == '?') return $base.$url; | |
// Parse base URL and convert to local variables: $scheme, $host, $path | |
extract(parse_url($base)); | |
// If no path, use / | |
if( ! isset($path)) $path = '/'; | |
// Remove non-directory element from path | |
$path = preg_replace('#/[^/]*$#', '', $path); | |
// Destroy path if relative url points to root | |
if($url[0] == '/') $path = ''; | |
// Dirty absolute URL | |
$abs = "$host$path/$url"; | |
// Replace '//' or '/./' or '/foo/../' with '/' | |
$re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#'); | |
for($n = 1; $n > 0; $abs = preg_replace($re, '/', $abs, -1, $n)) {} | |
// Absolute URL is ready! | |
return $scheme.'://'.$abs; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment