Dowemo
0 0 0 0


Question:

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

I use this:

dirname($_SERVER["PHP_SELF"])

But it won't work when it's included by another file in a different directory.

EDIT

I need a relative path to document root .It's used in web application.

I find there is another question with the same problem,but no accepted answer yet.

PHP - Convert File system path to URL


Best Answer:


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.jpgYour 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'));



Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs