URL Function Enhancements
One of the most commonly code snippets i’ve needed in both Perl and PHP over the years has been a function to neatly split URLs. While PHP’s parse_url function does this nicely; I also wanted to be able to echo a single piece of that result and enhance it with some commonly used ones.
The first function is fairly straight forward, build a URL out of the $\_SERVER global bits. This can be used with the second function for returning more interesting things. The parameter for get\_myurl() is an indication of wether the result should be echo’d or returned (a-la WordPress functions).
$res = ( $_SERVER[‘HTTPS’] ? ‘https://’ : ‘http://’ ) .
$_SERVER[‘HTTP_HOST’] .
$_SERVER[‘REQUEST_URI’];
if(!$v) { echo $res; } else { return $res; }
}
The second function is split\_url which is my enhancement on PHP’s builtin parse\_url.
It may be called like:
(Note: relpath is the relative path for the URL supplied (or from get\_myurl() if no URL is supplied), it is the path that any documents referenced in the current document would be relative to, unless a base href is supplied in the output.)
if($url == ‘’) { $url = get_myurl(true); }
$res = parse_url($url);
$res[‘fullpath’] = $res[‘path’];
$paths = explode(‘/’, $res[‘fullpath’]);
$res[‘file’] = array_pop($paths);
$res[‘path’] = implode(‘/’, $paths);
list($res[‘noquery’], $junk) = explode(‘/’, $res[’scheme’], 2);
$res[‘relpath’] = $res[’scheme’] . ‘://’;
if($res[‘username’]) { $res[‘relpath’] .= $res[‘user’] . ‘:’ . $res[‘pass’] . ‘@’; }
$res[‘relpath’] .= $res[‘host’] . $res[‘path’] . ‘/’;
if($component) {
if($v) { echo $res[$component]; return } else { return $res[$component];
}
return($res);
}
split\_url() with no arguments would return a associate array of all parts of the current URL.