Home » Php » php – Get folder up one level

php – Get folder up one level

Posted by: admin April 23, 2020 Leave a comment

Questions:

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 ?

How to&Answers:

You could do either:

dirname(__DIR__);

Or:

__DIR__ . '/..';

…but in a web server environment you will probably find that you are already working from current file’s working directory, so you can probably just use:

'../'

…to reference the directory above. You can replace __DIR__ with dirname(__FILE__) before PHP 5.3.0.

You should also be aware what __DIR__ and __FILE__ refers to:

The full path and filename of the file. If used inside an include, the name of the included file is returned.

So it may not always point to where you want it to.

Answer:

You can try

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

Answer:

echo dirname(__DIR__);

But note the __DIR__ constant was added in PHP 5.3.0.

Answer:

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

Answer:

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

Answer:

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