dpcj32769 2015-01-17 08:16
浏览 77
已采纳

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

I am using session variable to hide a log in form after user logs in. Here are first two lines from the PHP webpage

<?php
session_start();

Now,this is the logout button which appears after a user has logged in but take disappears only after two clicks

<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();
}?>

Here is code snippet from login form

<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="">

After succesful login I set $_SESSION['login'] = true; $_SESSION['user'] = $memberinfo['USER'];

Why do I have to click two times to keep get the forms work as expected?

EDIT Here is the complete code with HTML and Javascript stripped out

    <?php
    session_start();
    $mysqli = new mysqli($db_hostname,$db_username,$db_password,$db_database);
    if (mysqli_connect_errno()) {
    printf("Connect failed: %s
", 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.
";
    $message.="To verify your account please click on the link below
";
    $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'){
    }?>
  • 写回答

1条回答 默认 最新

  • duanhunlou7051 2015-01-17 08:20
    关注

    Destroy session should come at the very top of the page [EDIT] followed by a redirect with a header() to reload the page (as suggested by, and who reminded me of..) by DarkBee.

    Also, here is what I would recommend to you for your page. Everything is notated:

    functions.php (new page containing your main functions)

    <?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.
    ";
                        $message    .=  "To verify your account please click on the link below
    ";
                        $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
    ", mysqli_connect_error());
                    exit();
                }
    
                return $mysqli;
            }
    
        // Start session
        session_start();
        $mysqli =   DBConnect(); ?>
    

    index.php (Whatever name this page is, I picked 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 } ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 准备学习小程序搭建,谁能手把手的教我啊?
  • ¥15 第一天重装配置python和opencv后第二天打开就成这样,瞎捣鼓搞出来文件夹还是没法联网
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥100 AT89C52单片机C语言调试之后再回答
  • ¥15 AT89C52单片机C语言串口助手发送数据包返回值
  • ¥15 C++数组中找第二小的数字程序纠错
  • ¥50 MATLAB APP 制作出现问题
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)