PHP 只获取目录路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2601885/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:04:31  来源:igfitidea点击:

PHP Get only directory path

phppathdirectory

提问by Adrian M.

I have:

我有:

$page_file_temp = $_SERVER["PHP_SELF"];

which will output: /templates/somename/index.php

这将输出: /templates/somename/index.php

I want to extract from that path only "/templates/somename/"

我只想从那条路径中提取 "/templates/somename/"

How can I do it? Thanks!

我该怎么做?谢谢!

回答by David

$page_directory = dirname($page_file_temp);

See dirname.

请参阅目录名

回答by NOTSermsak

Maybe this is your solution:

也许这是您的解决方案:

$rootPath = $_SERVER['DOCUMENT_ROOT'];
$thisPath = dirname($_SERVER['PHP_SELF']);
$onlyPath = str_replace($rootPath, '', $thisPath);

For example:

例如:

$_SERVER['DOCUMENT_ROOT']is the server's root-path like this /home/abc/domains/abc.com/public_html

$_SERVER['DOCUMENT_ROOT']服务器的根路径是这样的 /home/abc/domains/abc.com/public_html

$_SERVER['PHP_SELF']is about the whole path to that script like this /home/abc/domains/abc.com/public_html/uploads/home/process.php

$_SERVER['PHP_SELF']是关于像这样的脚本的整个路径 /home/abc/domains/abc.com/public_html/uploads/home/process.php

Then we can have:

那么我们可以有:

$rootPathlike this /home/abc/domains/abc.com/public_html

$rootPath像这样 /home/abc/domains/abc.com/public_html

$thisPathlike this /home/abc/domains/abc.com/public_html/uploads/home

$thisPath像这样 /home/abc/domains/abc.com/public_html/uploads/home

And $onlyPathlike this /uploads/home

$onlyPath像这样/uploads/home

回答by Dominic Barnes

Using parse_urlwill account for GET variables and "fragments" (portion of URL after #) amongst other URL-specific parts.

使用parse_url将考虑 GET 变量和“片段”(# 之后的 URL 部分)以及其他特定于 URL 的部分。

$url = $_SERVER['PHP_SELF']; // OR $_SERVER['REQUEST_URI']

echo parse_url($url, PHP_URL_PATH);

回答by Yacoby

Take a look at the dirname()function.

看看dirname()函数。

From the documents, dirname()removes the trailing slash. If you want to keep it you can append the constant DIRECTORY_SEPARATOR to the result.

从文档中dirname()删除尾部斜杠。如果您想保留它,您可以将常量 DIRECTORY_SEPARATOR 附加到结果中。

$dir = dirname('mystring/and/path.txt').DIRECTORY_SEPARATOR;

回答by deadkarma

An alternative:

替代:

$directory = pathinfo($page_file_temp,PATHINFO_DIRNAME);

$directory = pathinfo($page_file_temp,PATHINFO_DIRNAME);

http://www.php.net/manual/en/function.pathinfo.php

http://www.php.net/manual/en/function.pathinfo.php