I have coded a function which converts relative URL to absolute URL for a project of mine. Considering I could not find it elsewhere, I figured I would post it here.
The following function takes in 2 parameters, the first parameter is the URL you want to convert from relative to absolute, and the second parameter is a sample of the absolute URL.
Currently it does not resolve '../' in the URL, only because I do not need it. Most webservers will resolve this for you. If you want it to resolve the '../' in the path, it just takes minor modifications.
<?php
function relativeToAbsolute($inurl, $absolute) {
$absolute_parts = parse_url($absolute);
if ( (strpos($inurl, $absolute_parts['host']) == false) ) {
$tmpurlprefix = "";
if (!(empty($absolute_parts['scheme']))) {
$tmpurlprefix .= $absolute_parts['scheme'] . "://";
}
if ((!(empty($absolute_parts['user']))) and (!(empty($absolute_parts['pass'])))) {
$tmpurlprefix .= $absolute_parts['user'] . ":" . $absolute_parts['pass'] . "@";
}
if (!(empty($absolute_parts['host']))) {
$tmpurlprefix .= $absolute_parts['host'];
if (!(empty($absolute_parts['port']))) {
$tmpurlprefix .= ":" . $absolute_parts['port'];
}
}
if ( (!(empty($absolute_parts['path']))) and (substr($inurl, 0, 1) != '/') ) {
$path_parts = pathinfo($absolute_parts['path']);
$tmpurlprefix .= $path_parts['dirname'];
$tmpurlprefix .= "/";
}
else {
$tmpurlprefix .= "/";
}
if (substr($inurl, 0, 1) == '/') { $inurl = substr($inurl, 1); }
if (substr($inurl, 0, 2) == './') { $inurl = substr($inurl, 2); }
return $tmpurlprefix . $inurl;
}
else {
return $inurl;
}
}
$absolute = "http://" . "user:pass@example.com:8080/path/to/index.html"; echo relativeToAbsolute($absolute, $absolute) . "\n";
echo relativeToAbsolute("img.gif", $absolute) . "\n";
echo relativeToAbsolute("/img.gif", $absolute) . "\n";
echo relativeToAbsolute("./img.gif", $absolute) . "\n";
echo relativeToAbsolute("../img.gif", $absolute) . "\n";
echo relativeToAbsolute("images/img.gif", $absolute) . "\n";
echo relativeToAbsolute("/images/img.gif", $absolute) . "\n";
echo relativeToAbsolute("./images/img.gif", $absolute) . "\n";
echo relativeToAbsolute("../images/img.gif", $absolute) . "\n";
?>
OUTPUTS:
http :// user:pass@example.com:8080/path/to/index.html
http :// user:pass@example.com:8080/path/to/img.gif
http :// user:pass@example.com:8080/img.gif
http :// user:pass@example.com:8080/path/to/img.gif
http :// user:pass@example.com:8080/path/to/../img.gif
http :// user:pass@example.com:8080/path/to/images/img.gif
http :// user:pass@example.com:8080/images/img.gif
http :// user:pass@example.com:8080/path/to/images/img.gif
http :// user:pass@example.com:8080/path/to/../images/img.gif
Sorry if the above code is not your style, or if you see it as "messy" or you think there is a better way to do it. I removed as much of the white space as possible.
Improvements are welcome :)