note 35227 added to function.realpath
| From: | dave at birko dot cjb dot net | Date: | Sun, 24 Aug 2003 11:04:45 +0000 |
| Subject: | note 35227 added to function.realpath | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-54985@lists.php.net to get a copy of this message | ||
This function is kind of reversed version of realpath. It takes
canonical ("absolute") path to a filename, $pic, and returns path
relative to the script's directory. I had to code it by myself as no
similar routine was to be found on the net. "POSIX" behaviour.
Tested on *nix.
Example:
The script is http://hostname/scripts/me.php
(realpath is
/var/www/application/scripts/me.php) and has only absolute path
to a picture (/var/www/data/pictures/image.jpg) it's about to
display using the tag <IMG> (which doesn't accept absolute
paths).
$rel = traverse_path("/var/www/data/pictures/image.jpg");
echo $rel;
../../data/pictures/image.jpg
The Code:
function traverse_path($pic) {
$from = dirname(realpath($_SERVER['DOCUMENT_ROOT'].
$_SERVER['SCRIPT_NAME']));
$to = dirname(realpath($pic));
$path = "../";
$i = 0;
// Find diff or the end of one of them
while (($from[$i] == $to[$i]) && $from[$i] && $to[$i++]);
$p = $i;
if (!$from[$i] && ($to[$i] == "/" || !$to[$i])) {
// $pic is in our (sub)directory
return ("./".substr($pic, $i+1, strlen($pic)));
} else {
// $pic is outside our dir branch
// find out how many "../"'s are necessary
while ($from[++$i]) {
if ($from[$i] == "/") $path .= "../";
}
// Find the first common dir
while ($to[--$p] != "/" && $to[$p]);
return ($path.substr($pic, $p+1, strlen($pic)));
}
}
Any fixes, ideas, etc. to my mail. Thx! :)
----
Manual Page -- http://www.php.net/manual/en/function.realpath.php
Edit Note -- http://master.php.net/manage/user-notes.php?action=edit+35227
Delete Note -- http://master.php.net/manage/user-notes.php?action=delete+35227&report=yes
Reject Note -- http://master.php.net/manage/user-notes.php?action=reject+35227&report=yes