PHP converts external relative path to absolute path

I am trying to figure out how to convert the “external relative path” to absolute: I would really like a function that will do the following:

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

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

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

And the value of $ abspath is " http://www.example.com/documentation/top.html "

The problem is that it is not guaranteed to be in this format, and it may already be absolute or completely point to another host, and I'm not quite sure how to approach this. Thanks.

+4
source share
3 answers

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

+2
source

So there are three cases:

  • correct url
  • no protocol
  • no protocol and domain

Code example (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"). 
+1
source

I seem to have solved 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 very well, for my purposes.

0
source

Source: https://habr.com/ru/post/1310316/


All Articles