[php] Get folder up one level

I am using this:

echo dirname(__FILE__);

which gives:

C:\UwAmp\www\myfolder\admin

However I am looking for path until:

C:\UwAmp\www\myfolder\

from current script. How can that be done ?

This question is related to php

The answer is


You can try

echo realpath(__DIR__ . DIRECTORY_SEPARATOR . '..'); 

Also you can use dirname(__DIR__, $level) for access any folding level without traversing


The parent directory of an included file would be

dirname(getcwd())

e.g. the file is /var/www/html/folder/inc/file.inc.php which is included in /var/www/html/folder/index.php

then by calling /file/index.php

getcwd() is /var/www/html/folder  
__DIR__ is /var/www/html/folder/inc  
so dirname(__DIR__) is /var/www/html/folder

but what we want is /var/www/html which is dirname(getcwd())


To Whom, deailing with share hosting environment and still chance to have Current PHP less than 7.0 Who does not have dirname( __FILE__, 2 ); it is possible to use following.

function dirname_safe($path, $level = 0){
    $dir = explode(DIRECTORY_SEPARATOR, $path);
    $level = $level * -1;
    if($level == 0) $level = count($dir);
    array_splice($dir, $level);
    return implode($dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
}

print_r(dirname_safe(__DIR__, 2));

echo dirname(__DIR__);

But note the __DIR__ constant was added in PHP 5.3.0.