PHP check if url parameter exists

99封情书 提交于 2019-11-27 11:26:53

问题


I have a URL which i pass parameters into

example/success.php?id=link1

I use php to grab it

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

then an if statement to display content based on parameter

<?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.

Thanks Guys


回答1:


Use isset()

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

EDIT: This is added for the completeness sake. $_GET in php is a reserved variable that 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.

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



回答2:


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

You want something like that




回答3:


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

Change your first line to

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



回答4:


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

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

I hope it will help you.




回答5:


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




回答6:


<?php
$link=parse_url("example/success.php?id=link1");
$slide=$_GET['id'];
if($slide=="link1"){
?>
//html content
<?php } ?>

I was trying to show search bar in navbar in only one php page and wanted to hide it in rest of the pages. This way it worked.



来源:https://stackoverflow.com/questions/18271173/php-check-if-url-parameter-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!