Let's say I have a URL of the document linking to another document (which can be both absolute or relative) and I need to have this link in absolute.
I made the simple function providing this functionality for several common cases:
function absolute_url($url,$parent_url){
$parent_url=parse_url($parent_url);
if(strcmp(substr($url,0,7),'http://')==0){
return $url;
}
elseif(strcmp(substr($url,0,1),'/')==0){
return $parent_url['scheme']."://".$parent_url['host'].$url;
}
else{
$path=$parent_url['path'];
$path=substr($path,0,strrpos($path,'/'));
return $parent_url['scheme']."://".$parent_url['host']."$path/".$url;
}
}
$parent_url='http://example.com/path/to/file/name.php?abc=abc';
echo absolute_url('name2.php',$parent_url)."\n";
// output http://example.com/path/to/file/name2.php
echo absolute_url('/name2.php',$parent_url)."\n";
// output http://example.com/name2.php
echo absolute_url('http://name2.php',$parent_url)."\n";
// output http://name2.php
The code works fine, but there could be more cases such as ../../path/to/file.php
which will not work.
So is there any standard classes or function doing this thing better (more universal) that my function?
I tried to Google it and check the similar questions (one and two) but it looks like server-path related solution which is not the thing I'm looking for.
This function will resolve relative URLs to a given current page url in
$pgurl
without regex. It successfully resolves:/home.php?example
types,same-dir
nextpage.php
types,../...../.../parentdir
types,full
http://example.net
urls,and shorthand
//example.net
urlsUsage Example:
nodots()
must be called after the URL is converted to absolute.The dots function is kind of redundant, but is readable, fast, doesn't use regex's, and will resolve 99% of typical urls (if you want to be 100% sure, just extend the switch block to support 6+ dots, although I've never seen that many dots in a URL).
Hope this helps,
There is probably a better/quicker way, but I just knocked this up...