Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to resolve a relative url

I need a function that given a relative URL and a base returns an absolute URL. I've searched and found many functions that do it different ways.

resolve("../abc.png", "http://example.com/path/thing?foo=bar") # returns http://example.com/abc.png 

Is there a canonical way?

On this site I see great examples for python and c#, lets get a PHP solution.

like image 879
Paul Tarjan Avatar asked Aug 07 '09 07:08

Paul Tarjan


People also ask

Is absolute URL better than relative?

An absolute URL contains more information than a relative URL does. Relative URLs are more convenient because they are shorter and often more portable. However, you can use them only to reference links on the same server as the page that contains them.

What is the difference between an absolute URL and a relative URL?

An absolute URL contains all the information necessary to locate a resource. A relative URL locates a resource using an absolute URL as a starting point. In effect, the "complete URL" of the target is specified by concatenating the absolute and relative URLs.

How do you find relative and absolute hyperlinks?

The main difference between absolute and relative paths is that absolute URLs always include the domain name of the site with http://www. Relative links show the path to the file or refer to the file itself. A relative URL is useful within a site to transfer a user from point to point within the same domain.


1 Answers

Perhaps this article could help?

http:// nashruddin.com/PHP_Script_for_Converting_Relative_to_Absolute_URL

Edit: reproduced code below for convenience

<?php     function rel2abs($rel, $base)     {         /* return if already absolute URL */         if (parse_url($rel, PHP_URL_SCHEME) != '' || substr($rel, 0, 2) == '//') return $rel;          /* queries and anchors */         if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;          /* parse base URL and convert to local variables:          $scheme, $host, $path */         extract(parse_url($base));          /* remove non-directory element from path */         $path = preg_replace('#/[^/]*$#', '', $path);          /* destroy path if relative url points to root */         if ($rel[0] == '/') $path = '';          /* dirty absolute URL */         $abs = "$host$path/$rel";          /* 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;     } ?> 
like image 138
Amber Avatar answered Oct 11 '22 22:10

Amber