php PHP检查url参数是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18271173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:16:00  来源:igfitidea点击:

PHP check if url parameter exists

phpurlurl-parameters

提问by user2389087

I have a URL which i pass parameters into

我有一个 URL,我将参数传递给它

example/success.php?id=link1

示例/success.php?id=link1

I use php to grab it

我用php来抓取它

$slide = ($_GET["id"]);

then an if statement to display content based on parameter

然后是一个 if 语句,根据参数显示内容

<?php  if($slide == 'link1') { ?>
   //content
 } ?>

Just need to know in PHP how to say, if the url param exists grab it and do the if function, if it doesn't exist do nothing.

只需要知道在 PHP 中怎么说,如果 url 参数存在则抓取它并执行 if 函数,如果它不存在则什么都不做。

Thanks Guys

谢谢你们

回答by Deepu

Use isset()

使用isset()

$matchFound = (isset($_GET["id"]) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

EDIT: This is added for the completeness sake. $_GETin php is a reserved variablethat is an associative array. Hence, you could also make use of 'array_key_exists(mixed $key, array $array)'. It will return a boolean that the key is found or not. So, the following also will be okay.

编辑:这是为了完整性而添加的。php 中的$_GET是一个保留变量,它是一个关联数组。因此,您还可以使用'array_key_exists(mixed $key, array $array)'。它将返回一个布尔值,表明是否找到了密钥。所以,下面的也没关系。

$matchFound = (array_key_exists("id", $_GET)) && trim($_GET["id"]) == 'link1');
$slide = $matchFound ? trim($_GET["id"]) : '';

回答by rich

if(isset($_GET['id']))
{
    // Do something
}

You want something like that

你想要这样的东西

回答by Your Common Sense

It is not quite clear what function you are talking about and if you need 2 separate branches or one. Assuming one:

目前还不清楚您在谈论什么功能,以及您是否需要 2 个单独的分支或一个。假设一:

Change your first line to

将您的第一行更改为

$slide = '';
if (isset($_GET["id"]))
{
    $slide = $_GET["id"];
}

回答by Faruque Ahamed Mollick

Here is the PHP code to check if 'id' parameter exists in the URL or not:

这是检查 URL 中是否存在“id”参数的 PHP 代码:

if(isset($_GET['id']))
{
   $slide = $_GET['id'] // Getting parameter value inside PHP variable
}

I hope it will help you.

我希望它会帮助你。

回答by jimshot

Why not just simplify it to if($_GET['id']). It will return true or false depending on status of the parameter's existence.

为什么不把它简化为 if($_GET['id'])。它将根据参数存在的状态返回真或假。