0 0 0 0


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

I use this:


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


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)));


You need to get relative path to file /var/www/ base path is /var/www/

Use the function like this:

$relative = getRelativePath('/var/www/','/var/www/');

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/','/var/www/'));

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs