doutang2017 2016-11-30 20:58
浏览 64
已采纳

isset和!empty始终为登录字段返回true

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>
  • 写回答

2条回答 默认 最新

  • dousi1906 2016-11-30 21:13
    关注

    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';
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?