douyi6168 2016-01-31 10:42
浏览 38
已采纳

具有会话登录表单的Mysqli和Php保持失败

When I hit my submit button to login nothing happens. I am just getting the same page, and not even an error. The connection to db should be fine. I have been looking at the code for 10 hours now, and I cannot figure out why. Does anybody have an idea?

dbconfic.inc.php:

<?php
    $db_host = "localhost";
    $db_user = "root";
    $db_pass = "root";
    $db_name  = "testdb";
    // connection:
    $mysqli = new mysqli($db_host, $db_user, $db_pass , $db_name);
    // tjek conenction:
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s
", mysqli_connect_error());
    }

    // vi kører utf-8 på connection:
    $mysqli->set_charset("utf-8");  
?>

index.php:

 <?php
include('login.php'); // Include Login Script

if(isset($_SESSION['username']))
{
header('Location: home.php');
}
exit();
?>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PHP Login Form with Session</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>
<h1>PHP Login Form with Session</h1>
<div class="loginBox">
<h3>Login Form</h3>
<br><br>
<form method="post" action="">
<label>Username:</label><br>
<input type="text" name="username" placeholder="username" /><br><br>
<label>Password:</label><br>
<input type="password" name="password" placeholder="password" />  <br><br>
<input type="submit" value="Login" /> 
</form>
<div class="error"><?php echo $error;?></div>
</div>
</body>
</html>

login.php:

<?php
session_start();
include("dbconfic.inc.php"); //Establishing connection with our database

$error = ""; //Variable for storing our errors.
if(isset($_POST["submit"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$error = "Both fields are required.";
}else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];

// To protect from MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($db, $username);
$password = mysqli_real_escape_string($db, $password);
$password = md5($password);

//Check username and password from database
$sql="SELECT uid FROM users WHERE username='$username' and password='$password'";
$result=mysqli_query($db,$sql);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);

//If username and password exist in our database then create a session.
//Otherwise echo error.

if(mysqli_num_rows($result) == 1)
{
$_SESSION['username'] = $login_user; // Initializing Session
header("location: home.php"); // Redirecting To Other Page
}else
{
$error = "Incorrect username or password.";
}

}
}

?>

home.php:

   <?php
    include("check.php");   
?>
 <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Home</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>

<body>
    <h1 class="hello">Hello, <em><?php echo $login_user;?>!</em></h1>
        <br><br><br>
    <a href="logout.php" style="font-size:18px">Logout?</a>
</body>
</html>

check.php:

<?php
include('dbconfic.inc.php');
session_start();
$user_check=$_SESSION['username'];

$sql = mysqli_query($db,"SELECT username FROM users WHERE username='$user_check' ");

$row=mysqli_fetch_array($sql,MYSQLI_ASSOC);

$login_user=$row['username'];

if(!isset($user_check))
{
header("Location: index.php");
}
?>

logout.php

<?php
session_start();
if(session_destroy())
{
header("Location: index.php");
}

?>
  • 写回答

2条回答 默认 最新

  • duandu8892 2016-01-31 11:21
    关注

    The index page seems more or less ok, a minor alteration to the use of isset and the inclusion of the login.php script.

    The check.php does an extra db lookup - you should be able just to use the session info to judge whether or not to redirect the user - so rather than echo $login_user in the html use $_SESSION['username']

    In the login.php script use prepared statements if possible to help mitigate against sql injection, and if possible avoid hashing passwords with md5!

    <?php
        $error='';
        if( !isset( $_SESSION ) ) session_start();
    
        if( !isset( $_SESSION['username'] ) ) include( login.php' );
        else exit( header('Location: home.php') );
    ?>
    <!doctype html>
    <html>
        <head>
            <meta charset='utf-8'>
            <title>PHP Login Form with Session</title>
            <link rel='stylesheet' href='style.css' type='text/css' />
        </head>
        <body>
            <h1>PHP Login Form with Session</h1>
            <div class='loginBox'>
                <h3>Login Form</h3>
                <br><br>
                <form method='post' action=''>
                    <label>Username:</label><br>
                    <input type='text' name='username' placeholder='username' /><br><br>
                    <label>Password:</label><br>
                    <input type='password' name='password' placeholder='password' /><br><br>
                    <input type='submit' name='submit' value='Login' /> 
                </form>
                <div class='error'><?php echo $error;?></div>
            </div>
        </body>
    </html>
    
    
    <?php
        /* login.php */
    
        $error = '';
    
        if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submit'], $_POST['username'], $_POST['password'] ) ) {
    
    
            if( empty( $_POST['username'] ) || empty( $_POST['password'] ) ){
    
                $error = 'Both fields are required.';
    
            }else {
    
                /* 
                    Use prepared statements - mitigates agsint sql injection.
                    Use placeholders in the sql which are used by the `bind_param` statement
                */
                $sql='select `uid` from `users` where `u_username`=? and `password`=? limit 1';
                $stmt=$db->prepare( $sql );
                if( !$stmt ) exit('Failed to prepare sql statement');
                /* 
                    md5 is not recommended for password hashing as it is generally considered to be broken
                    bind the variables to the placeholders & execute the sql
                */
                $username=$_POST['username'];
                $password=md5( $_POST['password'];
                $stmt->bind_param('ss', $username, $password ) );
                $res=$stmt->execute();
    
    
                /* bind the result of the query to a variable */
                $stmt->bind_result( $login_user );
                while( $stmt->fetch() ){
                    /* go through recordset ( 1 record ) */
                    $_SESSION['username'] = $login_user;
                }
    
                $stmt->close();
                $db->close();
    
                if( isset( $_SESSION['username'] ) ) exit( header( 'location: home.php' ) );
                else $error='Incorrect username or password.';
            }
        }
    ?>
    
    
    
    <?php
        /* home.php */
        if( !isset( $_SESSION ) ) session_start();
        if( !isset( $_SESSION[ 'username' ] ) ) exit( header('Location: index.php') );
        #include("check.php");  /* serves no real purpose once session is set */ 
    ?>
     <!doctype html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>Home</title>
            <link rel="stylesheet" href="style.css" type="text/css" />
        </head>
    
        <body>
            <h1 class="hello">Hello, <em><?php echo $_SESSION['username'];?>!</em></h1>
            <br><br><br>
            <a href="logout.php" style="font-size:18px">Logout?</a>
        </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号