如何使用PHP获取URL参数?
我试图获取每个 URL 参数并从头到尾显示它们,但我希望能够在页面上的任何位置显示任何参数。我该怎么做?我需要在脚本中添加或修改哪些内容?
以下是 URL 值的示例。
http://www.localhost.com/topics/index.php?cat=3&sub1=sub-1&sub2=sub-2&sub3=sub-3&sub4=sub-4
这是我的 PHP 脚本。
$url = $_SERVER['QUERY_STRING'];
$query = array();
if(!empty($url)){
foreach(explode('&', $url) as $part){
list($key, $value) = explode('=', $part, 2);
$query[$key] = $value;
}
}
I'm trying to grab each URL parameter and display them from first to last, but I want to be able to display any of the parameters anywhere on the page. How can I do this? What do I have to add or modify on my script?
Here is an example of a URL value.
http://www.localhost.com/topics/index.php?cat=3&sub1=sub-1&sub2=sub-2&sub3=sub-3&sub4=sub-4
Here is my PHP script.
$url = $_SERVER['QUERY_STRING'];
$query = array();
if(!empty($url)){
foreach(explode('&', $url) as $part){
list($key, $value) = explode('=', $part, 2);
$query[$key] = $value;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不需要手动执行此操作,PHP 已经在 $_GET 全局变量中提供了此功能:
You don't need to do that manually, PHP already provides this functionality in the $_GET global variable:
如果是 GET 请求,则所有参数都将位于 $_GET 中。表单 POST 将位于 $_POST 中。两者都包含在 $_REQUEST 中。
If it is a GET request, then all the params will be in $_GET. A form POST will be in $_POST. Both are contained in $_REQUEST.
您正在寻找
$_GET
超全局您可以使用此代码
$_GET['sub1']
访问任何$_GET
值,这将返回sub-1
You're looking for the
$_GET
superglobalYou can access any
$_GET
values by using this code$_GET['sub1']
which will returnsub-1
有一种比使用循环更简单的方法可以做到这一点。使用内置函数 parse_str()。它将请求 uri 拆分为 key =>值对。例子:
There is a much simpler way to do this rather than using a loop. Use the built in function parse_str(). It will split the request uri into key => value pairs. Example: