views:

486

answers:

3

Hello, I am trying to figure out how to convert an "external relative path" to an absolute one: I'd really like a function that will do the following:

$path = "/search?q=query";
$host = "http://google.com";
$abspath = reltoabs($host, $path);

And have $abspath equal to "http://google.com/search?q=query" Another example:

$path = "top.html";
$host = "www.example.com/documentation";
$abspath = reltoabs($host, $path);

And have $abspath equal to "http://www.example.com/documentation/top.html"

The problem is that it is not guaranteed to be in that format, and it could already be absolute, or be pointing to a different host entirely, and I'm not quite sure how to approach this. Thanks.

+1  A: 

So there are three cases:

  1. proper URL
  2. no protocol
  3. no protocol and no domain

Example code (untested):

if (preg_match('@^http(?:s)?://@i', $userurl))
    $url = preg_replace('@^http(s)?://@i', 'http$1://', $userurl); //protocol lowercase
//deem to have domain if a dot is found before a /
elseif (preg_match('@^[^/]+\\.[^/]+@', $useurl)
    $url = "http://".$useurl;
else { //no protocol or domain
    $url = "http://default.domain/" . (($useurl[0] != "/") ? "/" : "") . $useurl;
}

$url = filter_var($url, FILTER_VALIDATE_URL);

if ($url === false)
    die("User gave invalid url").
Artefacto
Three cases for the path or the host?
CMC
A: 

It appears I have answered my own problem:

function reltoabs($host, $path) {
    $resulting = array();
    $hostparts = parse_url($host);
    $pathparts = parse_url($path);
    if (array_key_exists("host", $pathparts)) return $path; // Absolute
    // Relative
    $opath = "";
    if (array_key_exists("scheme", $hostparts)) $opath .= $hostparts["scheme"] . "://";
    if (array_key_exists("user", $hostparts)) {
        if (array_key_exists("pass", $hostparts)) $opath .= $hostparts["user"] . ":" . $hostparts["pass"] . "@";
        else $opath .= $hostparts["user"] . "@";
    } elseif (array_key_exists("pass", $hostparts)) $opath .= ":" . $hostparts["pass"] . "@";
    if (array_key_exists("host", $hostparts)) $opath .= $hostparts["host"];
    if (!array_key_exists("path", $pathparts) || $pathparts["path"][0] != "/") {
        $dirname = explode("/", $hostparts["path"]);
        $opath .= implode("/", array_slice($dirname, 0, count($dirname) - 1)) . "/" . basename($pathparts["path"]);
    } else $opath .= $pathparts["path"];
    if (array_key_exists("query", $pathparts)) $opath .= "?" . $pathparts["query"];
    if (array_key_exists("fragment", $pathparts)) $opath .= "#" . $pathparts["fragment"];
    return $opath;
}

Which seems to work pretty well, for my purposes.

CMC
+2  A: 

You should try the PECL function http_build_url http://es2.php.net/manual/en/function.http-build-url.php

PerroVerd