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

后端 未结 5 1561
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  旧时难觅i
    2020-12-05 20:29

    PHP < 5.3:

    dirname(__FILE__)

    PHP >= 5.3:

    __DIR__

    EDIT:

    Here is the code to get path of included file relative to the path of running php file:

        $thispath = explode('\\', str_replace('/','\\', dirname(__FILE__)));
        $rootpath = explode('\\', str_replace('/','\\', dirname($_SERVER["SCRIPT_FILENAME"])));
        $relpath = array();
        $dotted = 0;
        for ($i = 0; $i < count($rootpath); $i++) {
            if ($i >= count($thispath)) {
                $dotted++;
            }
            elseif ($thispath[$i] != $rootpath[$i]) {
                $relpath[] = $thispath[$i]; 
                $dotted++;
            }
        }
        print str_repeat('../', $dotted) . implode('/', array_merge($relpath, array_slice($thispath, count($rootpath))));
    

提交回复
热议问题