简体   繁体   English

获取当前页面不完整的URL

[英]get current page not full url

Is it possible to save the current page in a variable (not the full url) using php 是否可以使用php将当前页面保存在变量(而不是完整的url)中

So if my page is www.mywebsite.com/news/bob 因此,如果我的页面是www.mywebsite.com/news/bob

I am looking to get /bob in a variable. 我正在寻找一个变量/bob

 <?PHP $file_name = $_SERVER['PHP_SELF']; ?>

see this variable 看到这个变量

$_SERVER['PATH_INFO']

maybe you need 也许你需要

basename($_SERVER['PATH_INFO']);

$_SERVER['PATH_INFO'] doesn't seem to exist on my install. $ _SERVER ['PATH_INFO']在我的安装中似乎不存在。 Not sure what the story is there, but if it's not on mine, it may not be on yours so here's some alternatives. 不知道其中的故事是什么,但是如果不是我的故事,那么它可能不在您的故事中,因此这里有一些替代方法。

$current_page = '/' . basename($_SERVER['PHP_SELF']);
$current_page = '/' . basename($_SERVER['REQUEST_URI']);
$current_page = '/' . basename($_SERVER['SCRIPT_NAME']);

I find $_SERVER['PHP_SELF'] to be quite dependable. 我发现$ _SERVER ['PHP_SELF']非常可靠。

If you're fond of regular expressions you could try 如果您喜欢正则表达式,可以尝试

$current_page = preg_replace('/(.*?\/)+(.*)$/', '/$2', $_SERVER['PHP_SELF']);

If you are using $_SERVER['PHP_SELF'] on included or required files, then it will return the current file, not the URL of the current page. 如果在包含或必需的文件上使用$ _SERVER ['PHP_SELF'],则它将返回当前文件,而不是当前页面的URL。 On Windows machines, the only reliable options are $_SERVER['REQUEST_URI'] or $_SERVER['HTTP_X_ORIGINAL_URL'] however, these will include any querystring as well. 在Windows计算机上,唯一可靠的选项是$ _SERVER ['REQUEST_URI']或$ _SERVER ['HTTP_X_ORIGINAL_URL'],但是,这些选项还将包括任何查询字符串。

You would need to strip the query string off the end of the URL to get the part you want. 您需要将查询字符串从URL末尾去除,以获得所需的部分。

$current_page = $_SERVER['REQUEST_URI'];
$current_page = substr($current_page, 0, strpos($current_page, "?")); //removes query string
$current_page =  = '/' . array_pop(array_filter(explode("/", $current_page)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM