PHP:从当前URL获取域后的路径


PHP: Get path after domain from current URL

我是PHP的初学者,所以请记住这一点。

我正试图从当前URL中获取JUST路径,它是可变的。例如,如果当前URL是http://example.com/blog/2014/blogpost.html,那么我希望得到/blog/2014或类似的东西。

这是我目前为止的PHP代码:

$full_url = $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$path_info =  parse_url($full_url,PHP_URL_PATH);
echo $path_info;

然而,这不起作用,我似乎无法在谷歌上找到合适的解决方案。

有人有什么线索吗?

提前感谢!

您可以使用strrpos来获取/的最后一个索引,并使用提取之前的URI部分

$req_uri = $_SERVER['REQUEST_URI'];
$path = substr($req_uri,0,strrpos($req_uri,'/'));

这将为您提供您想要的(/blog/2014

下面的例子应该会给你"/blog/2014/":

$path_info = substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], $_SERVER['SCRIPT_FILENAME']));

您可以这样做:

$url = "http://example.com/blog/2014/blogpost.html" ;
$parts = explode('/' , $url );
// then use any part of $parts by using $parts[i]