note 48217 deleted from function.realpath by irchtml
| From: | irchtml@php.net | Date: | Wed, 22 Dec 2004 09:38:38 +0000 |
| Subject: | note 48217 deleted from function.realpath by irchtml | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-82169@lists.php.net to get a copy of this message | ||
Note Submitter: carlosreche at yahoo dot com
----
Here is a little function that can be much helpful. It is an emulation of PHP's realpath(),
with the difference that the paramater may be a virtual file and it won't return always the
absolute path, it'll return a path in the same style of the original given by the user... so
you can use absolute and relative paths, and URLs.
Have fun! :)
Carlos Reche
<?php
function real_path($path)
{
if ($path == "")
{
return false;
}
$path = trim(preg_replace("/\\\\/", "/", (string)$path));
if (!preg_match("/(\.\w{1,4})$/", $path) &&
!preg_match("/\?[^\\/]+$/", $path) &&
!preg_match("/\\/$/", $path))
{
$path .= '/';
}
$pattern = "/^(\\/|\w:\\/|https?:\\/\\/[^\\/]+\\/)?(.*)$/i";
preg_match_all($pattern, $path, $matches, PREG_SET_ORDER);
$path_tok_1 = $matches[0][1];
$path_tok_2 = $matches[0][2];
$path_tok_2 = preg_replace(
array("/^\\/+/", "/\\/+/"),
array("", "/"),
$path_tok_2);
$path_parts = explode("/", $path_tok_2);
$real_path_parts = array();
for ($i = 0; $i < count($path_parts); $i++)
{
if ($path_parts[$i] == '.')
{
continue;
}
else if ($path_parts[$i] == '..')
{
array_pop($real_path_parts);
continue;
}
array_push($real_path_parts, $path_parts[$i]);
}
return $path_tok_1 . implode('/', $real_path_parts);
}
// Examples
$path_1 = 'C://////////Windows//////System';
$path_2 = 'C:\HTML\javascript\..\examples\colors.html';
$path_3 = '/root/./wwwroot/scripts/../././webpage';
$path_4 = 'wwwroot/webpage/../index.php?querystring';
$path_5 = 'http://www.php.net/manual/en/../../downloads';
$path_6 = 'http://www.php.net/downloads/.././docs.php';
/*
Returns:
C:/Windows/System/
C:/HTML/examples/colors.html
/root/wwwroot/webpage/
wwwroot/index.php?querystring
http://www.php.net/downloads/
http://www.php.net/docs.php
*/
echo '<pre>';
echo "\n\n" . $path_1 . " => " . real_path($path_1);
echo "\n\n" . $path_2 . " => " . real_path($path_2);
echo "\n\n" . $path_3 . " => " . real_path($path_3);
echo "\n\n" . $path_4 . " => " . real_path($path_4);
echo "\n\n" . $path_5 . " => " . real_path($path_5);
echo "\n\n" . $path_6 . " => " . real_path($path_6);
echo '</pre>';
?>