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?
CodePudding user response:
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)