Nicholas Hassan Nicholas Hassan - 8 days ago 8
HTML Question

isset and !empty always returns true for login field

I'm trying to create a php file (login.php) that can check the login field and validate the username and password. At the moment, it's just checking username using regex. Below is my code. I can't trigger the second else clause, it seems that isset and !empty are always true, even when I can see that they're visually empty, like immediately after refreshing the page.

<?php
if (isset($_POST['login']) && !empty($_POST['login'])) {
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST['username'])) {
echo 'set';
}
else {
echo 'wrong';
}
} else {
echo 'required field';
}
?>

<div id="login"> <!-- Login field with link to registration -->
<form method="POST" action="login.php">
<Legend>Login</Legend>
Username <input type="text" name="username"/>
Password <input type="password" name="password"/>
<input type="submit" name="login">
<div id="register">
<a href="registration.html">Not a member? Click here to register!</a>
</div>
</form>
</div>

Answer

I would suggest something more like this. First, check if $_POST['login'] is set first, so that you won't check anything else if the submit button hasn't been clicked yet. Then inside that, verify that username and password have been entered. If they have, go on with however you're going to validate them.

if (isset($_POST['login'])) {
    if (empty($_POST['username']) || empty($_POST['password'])) {
        echo 'required field';
    } else {
        if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST['username'])) {
            echo 'set';
        }
        else {
            echo 'wrong';
        }
    }
}