note 94725 deleted from function.realpath by danbrown

From: Date: Fri, 20 Nov 2009 17:18:46 +0000
Subject: note 94725 deleted from function.realpath by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-163135@lists.php.net to get a copy of this message
Note Submitter: mercury at caucasus dot net ---- 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); }

« previous php.notes (#163135) next »