Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

path

php

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

like image 995
user198729 Avatar asked Jan 19 '10 02:01

user198729


People also ask

How can I get full image path in PHP?

If you mean the path where the image was located on the user computer before he/she uploaded it to your form - you can never know it in php or javascript or anywhere else. In PHP you can see the path on SERVER (usually in the temporary folder) where the file was stored so you can read or copy it.

What is __ DIR __ in PHP?

The __DIR__ can be used to obtain the current code working directory. It has been introduced in PHP beginning from version 5.3. It is similar to using dirname(__FILE__). Usually, it is used to include other files that is present in an included file.

What is relative path in PHP?

Relative pathsIf you don't supply the root, it means that your path is relative. The simplest example of relative path is just a file name, like index. html . So one should be careful with relative paths. If your current directory is /about/ then index.


4 Answers

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']))));
like image 73
Alix Axel Avatar answered Oct 06 '22 00:10

Alix Axel


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))));
like image 25
Lukman Avatar answered Oct 05 '22 23:10

Lukman


Here's a general purpose function to get the relative path between two paths.

/**
 * Return relative path between two sources
 * @param $from
 * @param $to
 * @param string $separator
 * @return string
 */
function relativePath($from, $to, $separator = DIRECTORY_SEPARATOR)
{
    $from   = str_replace(array('/', '\\'), $separator, $from);
    $to     = str_replace(array('/', '\\'), $separator, $to);

    $arFrom = explode($separator, rtrim($from, $separator));
    $arTo = explode($separator, rtrim($to, $separator));
    while(count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0]))
    {
        array_shift($arFrom);
        array_shift($arTo);
    }

    return str_pad("", count($arFrom) * 3, '..'.$separator).implode($separator, $arTo);
}

Examples

relativePath('c:\temp\foo\bar', 'c:\temp');              // Result: ../../
relativePath('c:\temp\foo\bar', 'c:\\');                 // Result: ../../../
relativePath('c:\temp\foo\bar', 'c:\temp\foo\bar\lala'); // Result: lala
like image 38
inquam Avatar answered Oct 05 '22 23:10

inquam


I know this is an old question but the solutions suggested using DOCUMENT_ROOT assume the web folder structure reflects the server folder structure. I have a situation where this isn't the case. My solution is as follows. You can work out how a server address maps to a web address if you have an example from the same mapped area folders. As long as the root php file that included this file is in the same mapped area you have an example.

$_SERVER['SCRIPT_FILENAME'] is the server address of this file and $_SERVER['PHP_SELF'] is the web relative version. Given these two you can work out what the web relative version of your file is from its server address (__FILE__) as follows.

function getCurrentFileUrl() {
    $file = __FILE__;
    $script = $_SERVER['SCRIPT_FILENAME'];
    $phpself = $_SERVER['PHP_SELF'];

    // find end of section of $file which is common to $script
    $i = 0;
    while($file[$i] == $script[$i]) {
        $i++;
    }
    // remove end section of $phpself that is the equivalent to the section of $script not included in $file. 
    $phpself = substr($phpself, 0, strlen($phpself)-(strlen($script)-$i));
    // append end section of $file onto result
    $phpself .= substr($file, $i, strlen($file)-$i);

    // complete address 
    return $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].$phpself;
}
like image 24
adamfowlerphoto Avatar answered Oct 06 '22 00:10

adamfowlerphoto