如何验证$ _GET是否存在? [英] How to verify if $_GET exists?

查看:366
本文介绍了如何验证$ _GET是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < body>所以,我有一些PHP代码看起来有点像这样: 
ID是

<?php
echo $ _GET [id]。 !;
?>

< / body>

现在,当我传递一个像 http:// localhost / myphp .php?id = 26 它可以正常工作,但如果没有像 http://localhost/myphp.php 这样的ID, :

  ID是
注意:未定义的索引:id在C:\xampp\htdocs\myphp第9行的.php

我已经寻找了解决这个问题的方法,但我找不到任何方法来检查URL变量存在。我知道必须有一种方法。

解决方案

您可以使用 isset function:

  if(isset($ _ GET ['id'])){
// id index exists





$ b

如果index不存在,您可以创建一个方便的函数来返回默认值:

 函数Get($ index,$ defaultValue){
return isset($ _ GET [$ index])? $ _GET [$ index]:$ defaultValue);
}

//如果没有设置$ _GET ['id'],则输出invalid id
回声Get('id','invalid id');

您也可以尝试同时验证它:

 函数GetInt($ index,$ defaultValue){
return isset($ _ GET [$ index])&& ctype_digit($ _ GET [$ index])
? (int)$ _ GET [$ index]
:$ defaultValue);
}

//如果未设置$ _GET ['id']或者不是数字,则输出0
echo GetInt('id',0);


So, I have some PHP code that looks a bit like this:

<body>
    The ID is 

    <?php
    echo $_GET["id"] . "!";
    ?>

</body>

Now, when I pass an ID like http://localhost/myphp.php?id=26 it works alright, but if there is no ID like just http://localhost/myphp.php then it outputs:

The ID is
Notice: Undefined index: id in C:\xampp\htdocs\myphp.php on line 9
!

I have searched for a way to fix this but I cannot find any way to check if a URL variable exists. I know there must be a way though.

解决方案

You can use isset function:

if(isset($_GET['id'])) {
    // id index exists
}

You can create a handy function to return default value if index doesn't exist:

function Get($index, $defaultValue) {
    return isset($_GET[$index]) ? $_GET[$index] : $defaultValue);
}

// prints "invalid id" if $_GET['id'] is not set
echo Get('id', 'invalid id');

You can also try to validate it at the same time:

function GetInt($index, $defaultValue) {
    return isset($_GET[$index]) && ctype_digit($_GET[$index])
            ? (int)$_GET[$index] 
            : $defaultValue);
}

// prints 0 if $_GET['id'] is not set or is not numeric
echo GetInt('id', 0);

这篇关于如何验证$ _GET是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆