How to get the relative directory no matter from where it's included in PHP?

后端 未结 5 1552
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 20:02

If it\'s Path_To_DocumentRoot/a/b/c.php,should always be /a/b.

I use this:

dirname($_SERVER[\"PHP_SELF\"])
<
5条回答
  •  执笔经年
    2020-12-05 20:29

    Here's a general purpose function to get the relative path between two paths.

    /**
     * Return relative path between two sources
     * @param $from
     * @param $to
     * @param string $separator
     * @return string
     */
    function relativePath($from, $to, $separator = DIRECTORY_SEPARATOR)
    {
        $from   = str_replace(array('/', '\\'), $separator, $from);
        $to     = str_replace(array('/', '\\'), $separator, $to);
    
        $arFrom = explode($separator, rtrim($from, $separator));
        $arTo = explode($separator, rtrim($to, $separator));
        while(count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0]))
        {
            array_shift($arFrom);
            array_shift($arTo);
        }
    
        return str_pad("", count($arFrom) * 3, '..'.$separator).implode($separator, $arTo);
    }
    

    Examples

    relativePath('c:\temp\foo\bar', 'c:\temp');              // Result: ../../
    relativePath('c:\temp\foo\bar', 'c:\\');                 // Result: ../../../
    relativePath('c:\temp\foo\bar', 'c:\temp\foo\bar\lala'); // Result: lala
    

提交回复
热议问题