如何验证$_GET是否存在?

2023-12-23

所以,我有一些看起来有点像这样的 PHP 代码:

<body>
    The ID is 

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

</body>

现在,当我传递一个 ID 时,比如http://localhost/myphp.php?id=26它工作正常,但如果没有像这样的 IDhttp://localhost/myphp.php然后它输出:

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

我已经寻找了解决此问题的方法,但找不到任何方法来检查 URL 变量是否存在。我知道一定有办法。


您可以使用isset功能:

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

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

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');

您也可以同时尝试验证一下:

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何验证$_GET是否存在? 的相关文章