php 如何验证 $_GET 是否存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12019684/
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 02:39:27  来源:igfitidea点击:

How to verify if $_GET exists?

phphtmlurlvariables

提问by Doorknob

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

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

<body>
    The ID is 

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

</body>

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

现在,当我传递一个像http://localhost/myphp.php?id=26它一样工作的 ID 时,但如果没有像刚才http://localhost/myphp.php那样的ID,它会输出:

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.

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

回答by Zbigniew

You can use issetfunction:

您可以使用isset功能:

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

回答by Makita

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

回答by Sammaye

Normally it is quite good to do:

通常这样做是很好的:

echo isset($_GET['id']) ? $_GET['id'] : 'wtf';

This is so when assigning the var to other variables you can do defaults all in one breath instead of constantly using ifstatements to just give them a default value if they are not set.

因此,当将 var 分配给其他变量时,您可以一口气完成所有默认值,而不是不断使用if语句来仅在未设置时为其提供默认值。

回答by Asaph

You can use the array_key_exists()built-in function:

您可以使用array_key_exists()内置函数:

if (array_key_exists('id', $_GET)) {
    echo $_GET['id'];
}

or the isset()built-in function:

isset()内置函数:

if (isset($_GET['id'])) {
    echo $_GET['id'];
}

回答by Baba

You are use PHP isset

您正在使用 PHP isset

Example

例子

if (isset($_GET["id"])) {
    echo $_GET["id"];
}

回答by Julien

Use and empty()whit negation (for test if not empty)

使用和empty()whit 否定(用于测试是否为空)

if(!empty($_GET['id'])) {
    // if get id is not empty
}

回答by illeas

Please try it:

请尝试一下:

if(isset($_GET['id']) && !empty($_GET['id'])){
   echo $_GET["id"];
 }