note 82011 deleted from function.realpath by nlopess
| From: | nlopess@php.net | Date: | Mon, 24 Mar 2008 17:19:59 +0000 |
| Subject: | note 82011 deleted from function.realpath by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-137458@lists.php.net to get a copy of this message | ||
Note Submitter: caio dot ariede at gmail dot com
----
my relative path function, not smallest but it was very usefull for me.
<?php
/**
* author: caio ariede at gmail dot com
* http://caioariede.com/
*/
function relativepath($dest = null)
{
$s = DIRECTORY_SEPARATOR;
$base = $_SERVER['SCRIPT_FILENAME'];
$dest = realpath(substr($base, 0, strrpos($base, $s)) . $s . $dest);
if (!file_exists($dest)) return false;
$file = substr($dest, strrpos($dest, $s) + 1);
$dest = substr($dest, 0, strrpos($dest, $s) + 1);
$curr = getcwd() . $s;
$similar_func = create_function('$x,$y,$z',
'$str = strlen($x) > strlen($y)
? array($x, $y)
: array($y, $x);
list($str1, $str2) = $str;
$r = "";
for($i=0;$str1[$i];$i++){
if ($str1[$i] != $str2[$i]) break;
$r .= $str1[$i];
};
$r = substr($r, 0, strrpos($r, $z));
return empty($r) || $r == $z ? null : $r;');
$similar = $similar_func($curr, $dest, $s);
if ($similar)
{
$back = substr_count(str_replace($similar, '', $curr), $s) - 1;
$dest = str_repeat('..' . $s, $back) . str_replace($similar . $s, '',
$dest);
}
else
{
$dest = str_repeat('..' . $s, substr_count($curr, $s) - 1) . substr($dest, 1);
}
return $dest . $file;
}
// test:
echo relativepath('../content/test/example.php');
/* output
- browser:
content/test/example.php
- terminal:
root@publici2-desktop:/home/publici# php /var/www/codigo/relativepath.php
../../var/www/codigo/content/test/example.php
*/
?>