Back to examples |
Not my code, but a handy function which takes an absolute URL and a relative URL and combines the two to make a new absolute path.
The function has been modified to ignore an absolute URL passed as relative ( basically anything that includes a schema ). |
<?php
$url = "http://www.goat.com/money/dave.html"; $rel = "../images/cheese.jpg"; $com = InternetCombineURL($url,$rel); // Returns http://www.goat.com/images/cheese.jpg
function InternetCombineUrl($absolute, $relative) { $p = parse_url($relative); if($p["scheme"])return $relative; extract(parse_url($absolute)); $path = dirname($path); if($relative{0} == '/') { $cparts = array_filter(explode("/", $relative)); } else { $aparts = array_filter(explode("/", $path)); $rparts = array_filter(explode("/", $relative)); $cparts = array_merge($aparts, $rparts); foreach($cparts as $i => $part) { if($part == '.') { $cparts[$i] = null; } if($part == '..') { $cparts[$i - 1] = null; $cparts[$i] = null; } } $cparts = array_filter($cparts); } $path = implode("/", $cparts); $url = ""; if($scheme) { $url = "$scheme://"; } if($user) { $url .= "$user"; if($pass) { $url .= ":$pass"; } $url .= "@"; } if($host) { $url .= "$host/"; } $url .= $path; return $url; }
?>
|