Sunday, April 10, 2011

Relative to absolute URL conversion / PHP

function absolute_url($base_url, $relative_url){
 $base_url_info = parse_url($base_url);
 $base_url_path = explode("/", $base_url_info["path"]);
 $base_url_file = $base_url_path[count($base_url_path)-1];
 unset($base_url_path[count($base_url_path)-1]);
 $relative_url_path = explode("/", $relative_url);
 if (parse_url($relative_url, PHP_URL_SCHEME) != ""){
  return $relative_url;
 }else{
  switch($relative_url_path[0]){
   case ".":
    unset($relative_url_path[0]);
    return absolute_url
    ( $base_url
    , implode("/",$relative_url_path)
    );
    break;
   case "..":
    unset($relative_url_path[0]);
    return absolute_url
    (  str_replace($base_url_info["path"], "", $base_url)
     . implode("/", $base_url_path)
    , implode("/", $relative_url_path)
    );
    break;
   case "":
    return str_replace($base_url_info["path"], "", $base_url)
    .  $relative_url
    ;
    break;
   default:
    return str_replace($base_url_info["path"], "", $base_url)
    .  implode("/", $base_url_path)
    .  "/"
    .  $relative_url
    ;
    break;
  }
 }
}

2 comments:

  1. Nice, but watch out for trailing slash on your base url:

    absolute_url('http://example.com/', '/blah')

    causes the protocol slashes to be nuked:

    http:example.com/blah

    ReplyDelete
  2. It's actually quite a bit more complicated than this. Consider:
    absolute_url('http://www.google.com/?q=foo', '?q=bar') should be: http://www.google.com/?q=bar.

    Take a look at this.

    ReplyDelete