Here is a block of code that has the function you need:
http://ca.php.net/manual/en/function.parse-url.php#76682
Edit: the above related function is changed with an example
<?php
var_dump(resolve_url('http://www.site.com/aa/folder/page1.php','folder2/page.php?x=y&z=a'));
var_dump(resolve_url('http://www.site.com/aa/folder/page1.php','/folder2/page2.php'));
function unparse_url($components) {
return $components['scheme'].'://'.$components['host'].$components['path'];
}
function resolve_url($base, $url) {
if (!strlen($base)) return $url;
if (!strlen($url)) return $base;
if (preg_match('!^[a-z]+:!i', $url)) return $url;
$base = parse_url($base);
if ($url{0} == "#") {
$base['fragment'] = substr($url, 1);
return unparse_url($base);
}
unset($base['fragment']);
unset($base['query']);
if (substr($url, 0, 2) == "//") {
return unparse_url(array(
'scheme'=>$base['scheme'],
'path'=>$url,
));
} else if ($url{0} == "/") {
$base['path'] = $url;
} else {
$path = explode('/', $base['path']);
$url_path = explode('/', $url);
array_pop($path);
$end = array_pop($url_path);
foreach ($url_path as $segment) {
if ($segment == '.') {
} else if ($segment == '..' && $path && $path[sizeof($path)-1] != '..') {
array_pop($path);
} else {
$path[] = $segment;
}
}
if ($end == '.') {
$path[] = '';
} else if ($end == '..' && $path && $path[sizeof($path)-1] != '..') {
$path[sizeof($path)-1] = '';
} else {
$path[] = $end;
}
$base['path'] = join('/', $path);
}
return unparse_url($base);
}
?>
source
share