dongsao8279 2015-06-16 19:42
浏览 23
已采纳

PHP提交自己的表单

I am trying to create a login page and have it to submit to itself and then redirect based on if user is authenticated. But for some reason everytime i submit, with wrong username or password, i would like it to show the log in screen again but it just shows blank. But if i login correctly then it works.

<?php 
if (!empty($_POST)){ 

require_once 'includes/db.php';

    if($user->login($_POST["username"], $_POST["password"]))
        echo "user is logged in";   
}else{
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>

<body>
<form action="" method="post">
<table align="center">
    <tr>
        <td>User name:</td>
        <td>Password: </td>
    </tr>
    <tr>
        <td><input type="text" name="username" /></td>
        <td><input type="password" name="password" /></td>
    </tr>
    <tr>
        <td><input type="submit" value="Login" /></td>
    </tr>
</table>
</form>
</body>
</html>
<?php
}
?>
  • 写回答

2条回答 默认 最新

  • douli2063 2015-06-16 19:46
    关注

    That's because your !empty($_POST) clause triggers because the $_POST variable isn't empty, as you just send some login credentials (they may be wrong but that doesn't matter).

    The else clause just triggers when nothing is sent, so basically whenever you submit anything with the form, if the login credentials are right user is logged in will appear and if they are wrong, nothing will be put out whatsoever.

    The easiest way to solve this would be to remove the else clause entirely and add exit() into the if clause checking the credentials like so:

    <?php 
        if (!empty($_POST)) { 
            require_once 'includes/db.php';
    
            if ($user->login($_POST["username"], $_POST["password"])) {
                echo "user is logged in";
    
                /* Add exit() if you don't want the form to show
                   up when login attempt was successful. */
            }
        }
    ?>
    
    <!-- HTML CODE -->
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料