dpcj32769
dpcj32769
2015-01-17 08:16

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 duanhunlou7051 6年前

    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 } ?>
    
    点赞 评论 复制链接分享

相关推荐