开发者

Enter absolute path, return relative path in PHP [duplicate]

This question already has answers here: 开发者_开发技巧 Closed 11 years ago.

Possible Duplicate:

Getting relative path from absolute path in PHP

When including PHP-Files I often use absolute paths like

/etc/..../index.php

As I don't own the server those files may not be found if the admin changes position of the files.

But trying to find the right path using

..

each time when changing files is a hassle.

Is there a function or script I can pass my

/etc/..../index.php

to for it to return the relative path I can use with include?


dirname(__FILE__) returns the current directory name dirname(dirname(__FILE__)) takes you one level up etc. its the best way to include files


__DIR__.'/../../../index.php'

DIR returns directory of the file it was called from.


Tomalak Geret'kal is right, there is an algorithm for you here: Getting relative path from absolute path in PHP

As an alternative function you can use one posted by http://iubito.free.fr in PHP manual in 2003:

/**
 * Return the relative path between two paths / Retourne le chemin relatif entre 2 chemins
 *
 * If $path2 is empty, get the current directory (getcwd).
 * @return string
 */
function relativePath($path1, $path2='') {
if ($path2 == '') {
    $path2 = $path1;
    $path1 = getcwd();
}

//Remove starting, ending, and double / in paths
$path1 = trim($path1,'/');
$path2 = trim($path2,'/');
while (substr_count($path1, '//')) $path1 = str_replace('//', '/', $path1);
while (substr_count($path2, '//')) $path2 = str_replace('//', '/', $path2);

//create arrays
$arr1 = explode('/', $path1);
if ($arr1 == array('')) $arr1 = array();
$arr2 = explode('/', $path2);
if ($arr2 == array('')) $arr2 = array();
$size1 = count($arr1);
$size2 = count($arr2);

//now the hard part :-p
$path='';
for($i=0; $i<min($size1,$size2); $i++)
{
    if ($arr1[$i] == $arr2[$i]) continue;
    else $path = '../'.$path.$arr2[$i].'/';
}
if ($size1 > $size2)
    for ($i = $size2; $i < $size1; $i++)
        $path = '../'.$path;
else if ($size2 > $size1)
    for ($i = $size1; $i < $size2; $i++)
        $path .= $arr2[$i].'/';

return $path;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜