note 85388 added to function.realpath
| From: | IsaacZ dot Schlueteriatfoohackdotcom at osu1 dot php dot net | Date: | Thu, 28 Aug 2008 02:02:01 +0000 |
| Subject: | note 85388 added to function.realpath | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-143907@lists.php.net to get a copy of this message | ||
If you need to resolve a url against a base url, as the browser does with anchor tags, then realpath
won't help, because it's not on your file system.
This function does that:
<?php
function resolve_href ($base, $href) {
// href="" ==> current url.
if (!$href) {
return $base;
}
// href="http://..." ==> href isn't relative
$rel_parsed = parse_url($href);
if (array_key_exists('scheme', $rel_parsed)) {
return $href;
}
// add an extra character so that, if it ends in a /, we don't lose the last piece.
$base_parsed = parse_url("$base ");
// if it's just server.com and no path, then put a / there.
if (!array_key_exists('path', $base_parsed)) {
$base_parsed = parse_url("$base/ ");
}
// href="/ ==> throw away current path.
if ($href{0} === "/") {
$path = $href;
} else {
$path = dirname($base_parsed['path']) . "/$href";
}
// bla/./bloo ==> bla/bloo
$path = preg_replace('~/\./~', '/', $path);
// resolve /../
// loop through all the parts, popping whenever there's a .., pushing otherwise.
$parts = array();
foreach (
explode('/', preg_replace('~/+~', '/', $path)) as $part
) if ($part === "..") {
array_pop($parts);
} elseif ($part) {
$parts[] = $part;
}
return (
(array_key_exists('scheme', $base_parsed)) ?
$base_parsed['scheme'] . '://' . $base_parsed['host'] :
""
) . "/" . implode("/", $parts);
}
?>
----
Server IP: 64.71.164.2
Probable Submitter: 63.250.222.254
----
Manual Page -- http://www.php.net/manual/en/function.realpath.php
Edit -- https://master.php.net/note/edit/85388
Del: integrated -- https://master.php.net/note/delete/85388/integrated
Del: useless -- https://master.php.net/note/delete/85388/useless
Del: bad code -- https://master.php.net/note/delete/85388/bad+code
Del: spam -- https://master.php.net/note/delete/85388/spam
Del: non-english -- https://master.php.net/note/delete/85388/non-english
Del: in docs -- https://master.php.net/note/delete/85388/in+docs
Del: other reasons-- https://master.php.net/note/delete/85388
Reject -- https://master.php.net/note/reject/85388
Search -- https://master.php.net/manage/user-notes.php