PHP表单需要提交两次以设置会话

时间:2014-03-25 04:14:05

标签: php forms

所以我试图在我的网站上实现登录,但由于某种原因,表单需要按两次提交才能有效登录。我完全不知道为什么

<?php
    session_start();
if(isset($_SESSION["username"])){
        print('<p>'.$_SESSION["username"]." is currently logged in");
        print('<form action="logout.php"><input type="submit" value="Log out"></form>');
    }
else{
print('<form action="index.php" method="post">
        Username: <input type="text" name="username"/><br/>
        Password: <input type="password" name="password"/><br/>
        <input type="submit" value="Log In" name="submit"/>
    </form>');
include('config.php');

if(isset($_POST['submit'])) {
    $username = mysql_real_escape_string(htmlentities($_POST['username']));
    $password = hash('sha256', mysql_real_escape_string(htmlentities($_POST['password'])));
    $mysqli = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
    $qstring = 'SELECT * FROM login WHERE username = "'.$username.'" AND password = "'.$password.'"';
    $result = $mysqli->query($qstring);
    if($result->num_rows ==1)
    {

        $_SESSION['username']=$username;
        $_SESSION['password']=$password;       
    }

4 个答案:

答案 0 :(得分:1)

首先,您需要设置session_start()。那你的问题是因为在第一次登录并设置会话后你不会重定向你的页面。因此,第一次页面登陆会话为空并且您登录并设置会话但没有重定向。当您再次提交时,它已经设置,因此它显示您已登录。因此,请将您的代码更改为

   if($result->num_rows ==1)
   {
     $_SESSION['username']=$username;
     $_SESSION['password']=$password;    
     header('Location: index.php');
   }

答案 1 :(得分:1)

由于您拥有登录的所有代码,处理和显示用户在用户成功登录后没有重定向的同一页面登录,因此需要2次提交才能看到登录页面。

我建议您将登录页面与当前的登录页面分成login.phphome.php

此外,您应该避免查询usernamepassword,您只需要检索username并比较password,同时避免将密码保存在会议非常不需要。

login.php会有:

<?php
session_start();
// Your database info
$db_host = '';
$db_user = '';
$db_pass = '';
$db_name = '';

if (isset($_SESSION['username']))
{
    // If the user is already logged in send to home
    header("Location: home.php");
}
else
{
    // if the user is not logged in but have submitted the login page, 
    // check its credentials and redirect to home page
    if (isset($_POST['submit']))
    {
        if (isset($_POST['username']) && isset($_POST['password']))
        {
            $con = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
            if ($con->connect_error)
            {
                die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
            }

            $sql = "SELECT username, password FROM login WHERE username = ?";
            if (!$result = $con->prepare($sql))
            {
                die('Query failed: (' . $con->errno . ') ' . $con->error);
            }

            if (!$result->bind_param('s', $_POST['username']))
            {
                die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
            }

            if (!$result->execute())
            {
                die('Execute failed: (' . $result->errno . ') ' . $result->error);
            }

            $result->store_result();
            if ($result->num_rows == 0)
            {
                die('No username found...');
            }

            $password = hash('sha256', $_POST['password']);
            $result->bind_result($db_username, $db_password);
            $result->fetch();

            if ($password == $db_password)
            {
                $_SESSION['username'] = $db_username;
                header("Location: home.php");
                exit;
            }
            else
            {
                $error = "Username or password does not match...";
            }
        }
        else
        {
            $error = "Fill the username and password to login...";
        }
    }
}
// Show the form and/or possible error messages to user if applicable
?>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<?php if (isset($error)) echo $error, '<br>'; ?>
<form method="POST" action="index.php">
<label>Username</label><br /><input type="text" name="username" value=""><br />
<label>Password</label><br /><input type="password" name="password" value=""><br />
<input type="submit" name="submit" value="Login">
</form>
</body>
</html>

home.php

<?php
session_start();
if (!isset($_SESSION['username']))
{
    // send user back to login page if he is not logged in
    header("Location: login.php");
    exit;
}
// show the home page
?>
<p><? echo $_SESSION["username"]; ?> is currently logged in.
<form action="logout.php">
<input type="submit" value="Log out">
</form>

答案 2 :(得分:1)

如果你发布的内容是你的完整和实际的生产代码,那么你有一些缺少关闭括号,我不确定你希望在第一个条件语句的内部或外部include('config.php');

另外,您正在混合SQL函数。 mysql_*mysqli_*不要混用。

此:

$username = mysql_real_escape_string(htmlentities($_POST['username']));
$password = hash('sha256', mysql_real_escape_string(htmlentities($_POST['password'])));

应更改为:

$username = mysqli_real_escape_string($mysqli,$_POST['username']);
$password = hash('sha256', mysqli_real_escape_string($mysqli,$_POST['password']));

并放在数据库连接下方。

这是值得怀疑的,但我觉得我需要提一下。如果你确实有一个名为start_session();的函数ok。如果没有,那么可能需要更改为session_start();

<?php
session_start();
//  start_session();
if(isset($_SESSION["username"])){
        print('<p>'.$_SESSION["username"]." is currently logged in");
        print('<form action="logout.php"><input type="submit" value="Log out"></form>');
    }
else{
print('<form action="index.php" method="post">
        Username: <input type="text" name="username"/><br/>
        Password: <input type="password" name="password"/><br/>
        <input type="submit" value="Log In" name="submit"/>
    </form>');
include('config.php');

} // first missing brace and unsure if you want
// your included file inside of it, or out.

if(isset($_POST['submit'])) {

    $mysqli = new mysqli( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
    $username = mysqli_real_escape_string($mysqli,$_POST['username']);
    $password = hash('sha256', mysqli_real_escape_string($mysqli,$_POST['password']));
    $qstring = 'SELECT * FROM login WHERE username = "'.$username.'" AND password = "'.$password.'"';
    $result = $mysqli->query($qstring);
    if($result->num_rows ==1)
    {
        $_SESSION['username']=$username;
        $_SESSION['password']=$password;
    }

} // second missing brace

答案 3 :(得分:0)

您的基本身份验证逻辑错误。

您当前的周期是:

First load:
    Not logged in -> show form
    Submit
Second load:
    Process form
    Set session
Third load:
    Validate session