简体   繁体   中英

PHP Correctly checking if a post variable is empty

What is the correct way to check if a $_POST['var'] variable is empty?

For example, say I have a page with a form that needs client side and server side validation, and if any of the validation fails then the errors are displayed on labels on the form. The same labels will be used to display the error messages from either failed client-side validation or failed server-side validation.

This means that in the label I would have to do something like this:

<?php
if (isset($_POST['var'])) {

    echo $_POST['var'];
}
else {

    echo 'Please ensure you have entered your details';
}

?>

However I have heard that it is wrong to check if a $_Post variable is set if theres a possibility it is empty?

This link may be useful: https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/

Use the empty function to check if a variable contents something:

<?php
if (isset($_POST['var']) && !empty($_POST['var'])) {
    echo $_POST['var'];
}
else {
    echo 'Please ensure you have entered your details';
}
?>

First check with isset() to ensure that field is set. But isset() doesn't confirm a POST variable has non empty data. To ensure that use empty()

<?PHP
if(isset($_POST['var']) && !empty($_POST['var'])) {
    echo $_POST['var'];
}
?>

Note that always check isset() before checking empty otherwise its totally meaningless to check if a variable even exists or not after checking if it's empty or not.

You can use:

if(isset($_POST['var']) && !is_null($_POST['var']) && !empty($_POST['var']))
{
echo $_POST['var'];

}

Here's a possible solution.

if (isset($_POST['var']))
{
    if (!empty($_POST['var']))
    {
        echo $_POST['var'];
    }
    else
    {
        echo 'Please ensure you have entered your details';
    }
}
else
{
    echo 'Please ensure you have entered your details';
} 

Why is !empty() alone not enough?

It appears that empty() doesn't generate any warnings if the variable is not set. So it is necessary for you to check that the variable exists, at first. empty() seems to essentially equate to !isset($var) || $var == false !isset($var) || $var == false as mentioned in the docs[1].

[1] http://in1.php.net/empty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM