php 将文件夹上一级
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9149483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get folder up one level
提问by Dev555
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 ?
从当前脚本。那怎么办?
回答by DaveRandom
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:
...但在 Web 服务器环境中,您可能会发现您已经在当前文件的工作目录中工作,因此您可能只需使用:
'../'
...to reference the directory above. You can replace __DIR__
with dirname(__FILE__)
before PHP 5.3.0.
...引用上面的目录。您可以替换__DIR__
使用dirname(__FILE__)
PHP 5.3.0之前。
You should also be aware what __DIR__
and __FILE__
refers to:
您还应该知道什么__DIR__
和__FILE__
指的是:
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.
所以它可能并不总是指向你想要的地方。
回答by Dan Soap
You can try
你可以试试
echo realpath(__DIR__ . DIRECTORY_SEPARATOR . '..');
回答by Ondrej Machulda
echo dirname(__DIR__);
But note the __DIR__
constant was added in PHP 5.3.0.
但请注意该__DIR__
常量是在 PHP 5.3.0 中添加的。
回答by Dmitry Blad
Also you can use
dirname(__DIR__, $level)
for access any folding level without traversing
您也可以
dirname(__DIR__, $level)
用于访问任何折叠级别而无需遍历
回答by gsl
The parent directory of an included file would be
包含文件的父目录将是
dirname(getcwd())
e.g. the file is /var/www/html/folder/inc/file.inc.phpwhich is included in /var/www/html/folder/index.php
例如,文件是 /var/www/html/folder/inc/file.inc.php,它包含在 /var/www/html/folder/index.php
then by calling /file/index.php
然后通过调用 /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/htmlwhich is dirname(getcwd())
但我们想要的是/var/www/html这是dirname(getcwd())
回答by Deniz Porsuk
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.
对于谁,处理共享托管环境并且仍然有机会拥有 Current PHP 低于 7.0 谁没有dirname( __FILE__, 2 );
它可以使用以下。
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));