tags:

views:

125

answers:

2

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.

http://stackoverflow.com/questions/1240462/php-convert-file-system-path-to-url

+3  A: 

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))));
Lukman
Ah, were were a tie answer until you posted the PHP 5.3 `__DIR__` constant. +1 Great answer
Doug Neiner
No,I need a relative path to document root.
editted with the code
Lukman
I've updated my question.
A: 

Do you have access to $_SERVER['SCRIPT_NAME']? If you do, doing:

dirname($_SERVER['SCRIPT_NAME']);

Should work. Otherwise do this:

In PHP < 5.3:

substr(dirname(__FILE__), strlen($_SERVER['DOCUMENT_ROOT']));

Or PHP >= 5.3:

substr(__DIR__, strlen($_SERVER['DOCUMENT_ROOT']));

You might need to realpath() and str_replace() all \ to / to make it fully portable, like this:

substr(str_replace('\\', '/', realpath(dirname(__FILE__))), strlen(str_replace('\\', '/', realpath($_SERVER['DOCUMENT_ROOT']))));
Alix Axel
Why was this down-voted?
Alix Axel
`dirname($_SERVER['SCRIPT_NAME'])` is not working after `url-rewrite`
`substr(dirname(__FILE__), strlen($_SERVER['DOCUMENT_ROOT']));` basically works,not perfect though.