当前网址的PHP问题 [英] PHP problems with current url
问题描述
当用户更改页面语言时,我使用当前网址"功能来获取当前链接
I use the "Current url" function to get the current link when user changing page language
$uri = explode('&', $_SERVER['REQUEST_URI']);
$uri = $uri[0];
$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$uri : "http://".$_SERVER['SERVER_NAME'].$uri;
问题是,当我有这样的链接时:
Problem is, when I have a link like this:
http://127.0.0.1/index.php?id=shop&id2=13&lang=lt
id2
当然会消失.我该怎么办?是否可能将id2
设置为与第二个&
一起使用 explode 或类似的东西?
id2
, of course, disappears. What can I do about this? It is possible if id2
is set to use explode with a second &
or something like this?
推荐答案
您可以在此处使用 parse_url 函数是一个例子:
You can use the parse_url function, here is an example:
$uri = parse_url( $_SERVER['REQUEST_URI']);
$protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
$url = $protocol . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'] . '?' . ( isset( $uri['query']) ? $uri['query'] : '');
在您的代码中没有看到您获得脚本文件名的位置,因此我使用了$_SERVER['SCRIPT_NAME']
.
I did not see in your code where you get the script's filename, so I used $_SERVER['SCRIPT_NAME']
.
我的错误,我没有看到您需要操作/删除最后一个$_GET
参数.这是有关如何使用与上述类似的方法以及 parse_str 来执行此操作的示例.请注意,无论lang
参数的位置如何,此方法都可以使用,它不必是查询字符串中的最后一个.
My mistake, I did not see that you need to manipulate / remove the last $_GET
parameter. Here is an example on how to do that using a method similar to the above in conjunction with parse_str. Note that this method will work regardless of the location of the lang
parameter, it does not have to be the last one in the query string.
$protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
$params = array();
if( isset( $_SERVER['QUERY_STRING']) && !empty( $_SERVER['QUERY_STRING']))
{
parse_str( $_SERVER['QUERY_STRING'], $params);
$params['lang'] = 'anything';
// unset( $params['lang']); // This will clear it from the parameters
}
// Now rebuild the new URL
$url = $protocol . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'] . ( !empty( $params) ? ( '?' . http_build_query( $params)) : '');
感谢@Yzmir Ramirez对第二个版本的改进,消除了对parse_url
的不必要调用.
Thanks to @Yzmir Ramirez for an improvement in the second version that eliminates the extraneous call to parse_url
.
这篇关于当前网址的PHP问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!