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条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题