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

后端 未结 5 1560
被撕碎了的回忆
被撕碎了的回忆 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:24

    I had to create something to what you need so here is the result. By giving a base directory you receive a relative path to a file starting from base directory. Function is pretty fast, 100,000 checks took 0.64s. on my server. And it works for both directories and files. It is linux compatible. Don't even try it on windows :)

         /**
         * Return a relative path to a file or directory using base directory. 
         * When you set $base to /website and $path to /website/store/library.php
         * this function will return /store/library.php
         * 
         * Remember: All paths have to start from "/" or "\" this is not Windows compatible.
         * 
         * @param   String   $base   A base path used to construct relative path. For example /website
         * @param   String   $path   A full path to file or directory used to construct relative path. For example /website/store/library.php
         * 
         * @return  String
         */
        function getRelativePath($base, $path) {
            // Detect directory separator
            $separator = substr($base, 0, 1);
            $base = array_slice(explode($separator, rtrim($base,$separator)),1);
            $path = array_slice(explode($separator, rtrim($path,$separator)),1);
    
            return $separator.implode($separator, array_slice($path, count($base)));
        }
    

    Usage

    You need to get relative path to file /var/www/example.com/media/test.jpg Your base path is /var/www/example.com

    Use the function like this:

    $relative = getRelativePath('/var/www/example.com','/var/www/example.com/media/test.jpg');
    

    Function will return /media/test.jpg.

    If you need only the /media part without a file use it like this:

    $relative = dirname(getRelativePath('/var/www/example.com','/var/www/example.com/media/test.jpg'));
    

提交回复
热议问题