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 ?
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.
You can try
echo realpath(__DIR__ . DIRECTORY_SEPARATOR . '..');
Also you can use
dirname(__DIR__, $level)
for access any folding level without traversing
dirname()
is PHP7+ only. It's an integer representing how many levels to go up.
Nov 30, 2020 at 16:01
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));
Use $_SERVER['DOCUMENT_ROOT']
For example if you want to access a folder above the root directory from anywhere
$_SERVER['DOCUMENT_ROOT']."/../myfolder/spl-auto.php"
or for your example C:\UwAmp\www\myfolder\admin
$admin = $_SERVER['DOCUMENT_ROOT']."/myfolder/admin/"
$myfolder = $_SERVER['DOCUMENT_ROOT']."/myfolder/"