Dr.Kameleon Dr.Kameleon - 18 days ago 4
PHP Question

Get main URL part in PHP

OK, this is what I'm trying to do (it's quite a quickie actually, but decided to post in case we come up with something smarter... :-))



That's what I was thinking of :

function getMainPart($url)
{
$parts = explode("/",$url);
return str_replace(end($parts),"",$url);
}


Do you have anything... smarter or better to suggest? Any ideas? (Or anything more universal/directly-supported-by-PHP?)

Answer

The "right" (albeit a lot more long-winded) way to do it:

function getMainPart ($url) {
    $parts = parse_url($url);
    if (!isset($parts['scheme'])) {
        return FALSE; // Not a valid, complete URL
    }
    $out = $parts['scheme'].'://';
    if (!empty($parts['user'])) {
        $out .= $parts['user'];
        if (!empty($parts['pass'])) {
            $out .= ':'.$parts['pass'];
        }
        $out .= '@';
    }
    $out .= $parts['host'];
    if (!empty($parts['port'])) {
        $out .= ':'.$parts['port'];
    }
    $out .= $parts['path'] == '/' ? '/' : dirname($parts['path']);
    return $out;
}