如何使用PHP获取URL参数?

发布于 2024-09-14 23:26:49 字数 475 浏览 1 评论 0原文

我试图获取每个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

空城缀染半城烟沙 2024-09-21 23:26:49

您不需要手动执行此操作,PHP 已经在 $_GET 全局变量中提供了此功能:

<?php
    foreach($_GET as $key => $value)
        echo $key . " : " . $value;
?>

You don't need to do that manually, PHP already provides this functionality in the $_GET global variable:

<?php
    foreach($_GET as $key => $value)
        echo $key . " : " . $value;
?>
于我来说 2024-09-21 23:26:49

如果是 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.

深海夜未眠 2024-09-21 23:26:49

您正在寻找 $_GET 超全局

 foreach ($_GET as $key => $value) {
    echo $key . ' -- ' . $value;
}

您可以使用此代码 $_GET['sub1'] 访问任何 $_GET 值,这将返回sub-1

You're looking for the $_GET superglobal

 foreach ($_GET as $key => $value) {
    echo $key . ' -- ' . $value;
}

You can access any $_GET values by using this code $_GET['sub1'] which will return sub-1

谁许谁一生繁华 2024-09-21 23:26:49

有一种比使用循环更简单的方法可以做到这一点。使用内置函数 parse_str()。它将请求 uri 拆分为 key =>值对。例子:

$url = "cat=3&sub1=sub-1&sub2=sub-2&sub3=sub-3&sub4=sub-4";
$query = array();
parse_str( $url, $query );
print_r($query);

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:

$url = "cat=3&sub1=sub-1&sub2=sub-2&sub3=sub-3&sub4=sub-4";
$query = array();
parse_str( $url, $query );
print_r($query);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文