如何验证 $_GET 是否存在?

2022-08-30 08:50:33

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

<body>
    The ID is 

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

</body>

现在,当我传递一个ID时,它工作正常,但是如果没有ID,那么它就会输出:http://localhost/myphp.php?id=26http://localhost/myphp.php

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

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


答案 1

您可以使用以下功能: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);

答案 2
   if (isset($_GET["id"])){
        //do stuff
    }

推荐