note 94725 added to function.realpath
| From: | mercury at caucasus dot net | Date: | Fri, 20 Nov 2009 15:10:38 +0000 |
| Subject: | note 94725 added to function.realpath | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-163126@lists.php.net to get a copy of this message | ||
This is a modified code originally provided by Isaac Z. Schlueter i at foohack dot com on
28-Aug-2008 02:02. This function resolves a url against a base url.
I substituted:
path = dirname($base_parsed['path']) . "/$href";
with:
$path = preg_replace("~/[^/]*$~", "/", $base_parsed['path']).$href;
dirname() function isn't suitable if you resolve a url, because it delimits path with
backslashes(\) instead of forward slashes (/), which results in malformed url.
The entire code looks like this:
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);
// I added this line
if(!array_key_exists('scheme', $base_parsed)) return false;
// 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 = preg_replace("~/[^/]*$~", "/", $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: 69.147.83.197
Probable Submitter: 62.168.164.191
----
Manual Page -- http://www.php.net/manual/en/function.realpath.php
Edit -- https://master.php.net/note/edit/94725
Del: integrated -- https://master.php.net/note/delete/94725/integrated
Del: useless -- https://master.php.net/note/delete/94725/useless
Del: bad code -- https://master.php.net/note/delete/94725/bad+code
Del: spam -- https://master.php.net/note/delete/94725/spam
Del: non-english -- https://master.php.net/note/delete/94725/non-english
Del: in docs -- https://master.php.net/note/delete/94725/in+docs
Del: other reasons-- https://master.php.net/note/delete/94725
Reject -- https://master.php.net/note/reject/94725
Search -- https://master.php.net/manage/user-notes.php