jvit
JVIT PHPparse url to protocol, host path ,file
Shortcut: url.parse
/**
* parse a full url or pathname and return an array(protocol, host, path,
* file + query + fragment)
*
* @param string $url
* @return array
*/
function parseUrl($url)
{
$protocol = "";
$host = "";
$path = "";
$file = "";
$res = "";
$arr = parse_url($url);
if (isset($arr["scheme"])) {
$arr["scheme"] = mb_strtolower($arr["scheme"]);
}
if (isset($arr["scheme"]) && $arr["scheme"] !== "file" && $arr["scheme"] !== "phar" && strlen($arr["scheme"]) > 1) {
$protocol = $arr["scheme"] . "://";
if (isset($arr["user"])) {
$host .= $arr["user"];
if (isset($arr["pass"])) {
$host .= ":" . $arr["pass"];
}
$host .= "@";
}
if (isset($arr["host"])) {
$host .= $arr["host"];
}
if (isset($arr["port"])) {
$host .= ":" . $arr["port"];
}
if (isset($arr["path"]) && $arr["path"] !== "") {
// Do we have a trailing slash?
if ($arr["path"][mb_strlen($arr["path"]) - 1] === "/") {
$path = $arr["path"];
$file = "";
} else {
$path = rtrim(dirname($arr["path"]), '/\\') . "/";
$file = basename($arr["path"]);
}
}
if (isset($arr["query"])) {
$file .= "?" . $arr["query"];
}
if (isset($arr["fragment"])) {
$file .= "#" . $arr["fragment"];
}
} else {
$protocol = "";
$host = ""; // localhost, really
$i = mb_stripos($url, "://");
if ($i !== false) {
$protocol = mb_strtolower(mb_substr($url, 0, $i + 3));
$url = mb_substr($url, $i + 3);
} else {
$protocol = "file://";
}
if ($protocol === "phar://") {
$res = substr($url, stripos($url, ".phar") + 5);
$url = substr($url, 7, stripos($url, ".phar") - 2);
}
$file = basename($url);
$path = dirname($url) . "/";
}
$ret = [
$protocol, $host, $path, $file,
"protocol" => $protocol,
"host" => $host,
"path" => $path,
"file" => $file,
"resource" => $res
];
return $ret;
}