note 85388 deleted from function.realpath by peehaa

From: Date: Sun, 28 Apr 2019 09:48:23 +0000
Subject: note 85388 deleted from function.realpath by peehaa
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-210709@lists.php.net to get a copy of this message
Note Submitter: Isaac Z. Schlueter i at foohack dot com ---- 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); } ?> [EDIT BY danbrown AT php DOT net: Code contains a bugfix supplied by (Zhenya DOT Morozov AT gmail DOT com) on 23-JAN-09, to address the following issue: 'If your path contains "0" (or any "false" string) directory name, the function removes that directory from the path.']

« previous php.notes (#210709) next »