PHP 表单需要点击两次提交按钮才能消失

PHP form requires two submit button clicks to disappear

我正在使用会话变量在用户登录后隐藏登录表单。这是 PHP 网页的前两行

<?php
session_start();

现在,这是用户登录后出现的注销按钮,但点击两次后才会消失

<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12" <?php if(!isset($_SESSION['login'])) echo 'style="display:none;"'; else echo 'style="display:block;"';?>/>
<form method="post" action="">
<p>Hey, <?php echo ''.$_SESSION['user'].''; ?></p>
<input style="border: none; padding: 8px 15px; background: #BAFF00; box-shadow: 0px 0px 3px #757875;" type="submit" name="submit" value="Logout">
</form>
<?php
if ($_POST['submit'] == 'Logout'){
session_destroy();
}?>

这是登录表单的代码片段

<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12" <?php if(isset($_SESSION['login'])) echo 'style="display:none;"'; else echo 'style="display:block;"';?>/>
<form method="post" action="">

登录成功后我设置 $_SESSION['login'] = true; $_SESSION['user'] = $memberinfo['USER'];

为什么我必须点击两次才能让表格按预期工作?

编辑 这是删除了 HTML 和 Javascript 的完整代码

    <?php
    session_start();
    $mysqli = new mysqli($db_hostname,$db_username,$db_password,$db_database);
    if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
    }
    if($passkey=$_GET['passkey']){
    $result=$mysqli->query("SELECT * FROM unactivated WHERE code ='$passkey'");
    if($result){
    $count=mysqli_num_rows($result);
    if($count==1){
    $rows=mysqli_fetch_array($result);
    $user=$rows['USER'];
    $email=$rows['EMAIL'];
    $password=$rows['PASSWORD'];
    $password=$mysqli->real_escape_string(hash_hmac('sha256',$password, 'c#haRl891', true));
    if($mysqli->query("INSERT INTO member ( USER, EMAIL, PASSWORD) VALUES ('$user', '$email', '$password')"))
    {
    echo "Your account has been activated";
    $mysqli->query("DELETE FROM unactivated WHERE code = '$passkey'");
    }}}
    else {
    echo "Wrong Confirmation code";
    }}?>
    <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12" <?php
if(isset($_SESSION['login'])) echo 'style="display:none;"'; else echo 'style="display:block;"';?>/>
    <form method="post" action="">
    <input class="form-control" type="text" name="user" placeholder="Alex Bruno (for Sign Up)" />
    <input class="form-control" type="email" name="email" placeholder="your@email.com" required />
    <input class="form-control" type="password" name="password" value="" placeholder="Strong Password" required />
    <p>Enter valid email to get a login link.</p>
    <input style="border: none; padding: 8px 15px; background: #BAFF00; box-shadow: 0px 0px 3px #757875;" type="submit" name="submit" value="Register">
    <input style="border: none; padding: 8px 15px; background: #BAFF00; box-shadow: 0px 0px 3px #757875; float:right;" type="submit" name="submit" value="Login">
    </form>
    <?php
    if ($_POST['submit'] == 'Register'){
    if (!empty($_REQUEST['user'])&&!empty($_REQUEST['email'])&&!empty($_REQUEST['password'])) {
    $user = $_POST['user'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $user = $mysqli->real_escape_string($user);
    $email = $mysqli->real_escape_string($email);
    $password = $mysqli->real_escape_string($password);
    $query = $mysqli->query("SELECT * from member WHERE EMAIL ='$email'");
    $rows = mysqli_num_rows($query);
    if ($rows == 0)
    {
    $code=md5(uniqid(rand()));
    $mysqli->query("INSERT INTO unactivated (CODE, USER, EMAIL, PASSWORD) VALUES ('$code', '$user', '$email', '$password')");
    $to=$email;
    $subject="Please verify your Sign Up";
    $header="from: 8mags <contact@8mags.com>";
    $message="You or someone else used this email address to sign up for 8mags. If you did not do it ignore the message.\n";
    $message.="To verify your account please click on the link below\n";
    $url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?passkey='.$code.'';
    $message.=$url;
    $sentmail = mail($to,$subject,$message,$header);
    if($sentmail){
    echo 'Your Confirmation link Has Been Sent To Your Email Address.';
    }}
    echo 'Email already registered!';
    }}
    if ($_POST['submit'] == 'Login'){
    $password=$mysqli->real_escape_string(hash_hmac('sha256',$password, 'c#haRl891', true));
    $query = $mysqli->query("SELECT * from member WHERE EMAIL = '$email' AND PASSWORD = '$password'");
    $rows = mysqli_num_rows($query);
    if($rows==1)
    {
    $memberinfo = mysqli_fetch_array($query);
    $_SESSION['login'] = true;
    $_SESSION['user'] = $memberinfo['USER'];
    }
    else{
    echo 'Entered Password and Email Combination is wrong!';
    }}?>
    <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12" <?php if(!isset($_SESSION['login'])) echo 'style="display:none;"'; else echo 'style="display:block;"';?>/>
    <form method="post" action="">
    <p>Hey, <?php echo ''.$_SESSION['user'].''; ?></p>
    <input style="border: none; padding: 8px 15px; background: #BAFF00; box-shadow: 0px 0px 3px #757875;" type="submit" name="submit" value="Logout">
    </form>
    <?php
    if ($_POST['submit'] == 'Logout'){
    }?>

销毁会话应该出现在页面的最顶部 [编辑],然后是带有 header() 的重定向以重新加载页面(如建议的,和谁让我想起了..)作者:DarkBee.

此外,这是我要为您的页面推荐的内容。一切都注明:

functions.php(包含您的主要功能的新页面)

<?php
    // You should make these functions and on
    // a separate page that you include
    function Login($checkpass, $checkemail, $mysqli)
        {
                $email      =   $mysqli->real_escape_string($checkemail);
                $password   =   $mysqli->real_escape_string(hash_hmac('sha256',$checkpass, 'c#haRl891', true));
                $query      =   $mysqli->query("SELECT * from member WHERE EMAIL = '$email' AND PASSWORD = '$password'");
                $rows       =   mysqli_num_rows($query);

                if($rows == 1) {
                    $memberinfo = mysqli_fetch_array($query);
                    $_SESSION['login']  =   true;
                    $_SESSION['user']   =   $memberinfo['USER'];
                    return true;
                }
        // Return false if failed
        return false;
    }

    function Register($mysqli)
        {
            if (!empty($_REQUEST['user'])&&!empty($_REQUEST['email'])&&!empty($_REQUEST['password'])) {
                $user       =   $_POST['user'];
                $email      =   $_POST['email'];
                $password   =   $_POST['password'];
                $user       =   $mysqli->real_escape_string($user);
                $email      =   $mysqli->real_escape_string($email);
                $password   =   $mysqli->real_escape_string($password);
                $query      =   $mysqli->query("SELECT * from member WHERE EMAIL ='$email'");
                $rows       =   mysqli_num_rows($query);

                if ($rows == 0) {
                    $code       =   md5(uniqid(rand()));
                    $mysqli->query("INSERT INTO unactivated (CODE, USER, EMAIL, PASSWORD) VALUES ('$code', '$user', '$email', '$password')");
                    $to         =   $email;
                    $subject    =   "Please verify your Sign Up";
                    $header     =   "from: 8mags <contact@8mags.com>";
                    $message    =   "You or someone else used this email address to sign up for 8mags. If you did not do it ignore the message.\n";
                    $message    .=  "To verify your account please click on the link below\n";
                    $url        =   "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].'?passkey='.$code.'';
                    $message    .=  $url;

                    // Return success
                    if(mail($to,$subject,$message,$header)){
                        return true;
                    }
                }
            }

            // Return fail by default
            return false;
        }

    function FetchPassKey($mysqli)
        {
            // This part is a bit scary, you are not binding or sanitizing this.
            // It's open to sql injection attacks
            $passkey    =   $_GET['passkey'];
            $result     =   $mysqli->query("SELECT * FROM unactivated WHERE code ='$passkey'");
            if($result) {
                    $count  =   mysqli_num_rows($result);
                    if($count==1){
                        $rows       =   mysqli_fetch_array($result);
                        $user       =   $rows['USER'];
                        $email      =   $rows['EMAIL'];
                        $password   =   $rows['PASSWORD'];
                        $password   =   $mysqli->real_escape_string(hash_hmac('sha256',$password, 'c#haRl891', true));

                        if($mysqli->query("INSERT INTO member ( USER, EMAIL, PASSWORD) VALUES ('$user', '$email', '$password')")) {
                            $mysqli->query("DELETE FROM unactivated WHERE code = '$passkey'");
                            return true;
                        }
                    }
                }

            return false;
        }
    ?>

config.php

<?php
    function DBConnect($db_hostname = 'host',$db_username = 'username',$db_password = 'password',$db_database = 'dbname')
        {
            // Database 
            $mysqli = new mysqli($db_hostname,$db_username,$db_password,$db_database);
            if(mysqli_connect_errno()) {
                printf("Connect failed: %s\n", mysqli_connect_error());
                exit();
            }

            return $mysqli;
        }

    // Start session
    session_start();
    $mysqli =   DBConnect(); ?>

index.php(不管这个页面叫什么名字,我都选了index.php)

    // Make a db function
    include_once('config.php');
    // Include the functions that run this page actions
    include_once('functions.php');
    // If logging out, destroy session
    if(isset($_POST['submit'])) {
        // Logout script
        if($_POST['submit'] == 'Logout') {
                session_destroy();
                header("Location: ".$_SERVER['PHP_SELF']);
                exit;
            }
        // Run your login script
        elseif($_POST['submit'] == 'Login')
            $valid  =   Login($_POST['password'],$_POST['email'],$mysqli);
        elseif($_POST['submit'] = 'Register')
            $registered =   Register($mysqli);
    }      

    // You are doing an equals here, should be double equal ==
    // or it will always be true
    if(isset($_GET['passkey']) && !empty($_GET['passkey'])){
        echo (FetchPassKey($mysqli) == true)? "Your account has been activated":"Wrong Confirmation code";
    }

    // Just don't print it to page
    if(!isset($_SESSION['login'])) { ?>
    <div style=" display: inline-block;" class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
        <form method="post" action="">
            <input class="form-control" type="text" name="user" placeholder="Alex Bruno (for Sign Up)" />
            <input class="form-control" type="email" name="email" placeholder="your@email.com" required />
            <input class="form-control" type="password" name="password" value="" placeholder="Strong Password" required />
            <p>Enter valid email to get a login link.</p>
            <input style="border: none; padding: 8px 15px; background: #BAFF00; box-shadow: 0px 0px 3px #757875;" type="submit" name="submit" value="Register">
            <input style="border: none; padding: 8px 15px; background: #BAFF00; box-shadow: 0px 0px 3px #757875; float:right;" type="submit" name="submit" value="Login">
        </form>
    </div>
    <?php }

    // Just echo the results of your register validate function
    if (isset($_POST['submit']) && $_POST['submit'] == 'Register')
        echo ($registered == true)?  'Your Confirmation link Has Been Sent To Your Email Address.':'Email already registered!';

    // Just echo the results of your validation here but assign and check at top.
    if(isset($valid) && $valid == false)
        echo 'Entered Password and Email Combination is wrong!';

    // Just display if logged in
    if(isset($_SESSION['login'])) { ?>
    <div class="col-lg-4 col-md-4 col-sm-6 col-xs-12" style="display:block;">
        <form method="post" action="">
            <p>Hey, <?php echo ''.$_SESSION['user'].''; ?></p>
            <input style="border: none; padding: 8px 15px; background: #BAFF00; box-shadow: 0px 0px 3px #757875;" type="submit" name="submit" value="Logout">
        </form>
    </div>
    <?php } ?>