简体   繁体   中英

If condition is meet but is ignored in PHP code

I have the following code to validate if a username is entered:

 if (!isset($_POST['username']) ) {
    
    header("location: index.php");
    $error_message = "Please enter your Username and Password!";
    exit();
 }

If I don't enter any value in the username field, the condition turns out false and would execute the code inside the if statement and similar situation when I enter a username!

Any idea why this is happening?

If you have a form with an <input name="username"> then this input will always have some sort of value. If you don't enter anything, the value is still the empty string. And of course that empty string is posted to the server.

On the other hand PHP isset checks

"if a variable is declared and is different than null"

And of course this is true even for the empty string (ie username exists and it's different from null ). If you want to catch all situations where your username is either not existing at all or an empty string you can for instance do as follows

if (!isset($_POST['username']) || trim($_POST['username']) === '' )

or you can use

if (strlen($_POST['username']) == 0)

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