如何检查用户登录并启动会话


How do I check a user login and start the session

所以我的网站有登录名,但用户必须登录才能查看每个页面,我不希望他们每次都登录 我想添加一个会话,所以他们只登录一次我需要在我的代码中添加什么,这样他们就不需要登录,直到他们点击注销。 http://pastebin.com/dbE3mAKV

在您的登录页面上添加这个;

 session_start();  
 $_SESSION['usename'] = $username;  
 $_SESSION['password'] = $password;  

并在所有其他页面上添加以下内容:

 session_start();  
 $username = $_SESSION['usename'];  
 $password = $_SESSION['password'];  
 # Do database check on $username and $password  
 if($username =='test' AND $password =='pass1'){  
     echo "logged in";  
 } else {  
     die("please log in first!");    
 }  

您可以使用

session_start来启动会话(必须在每个页面上调用才能工作)。有关一般会话的更多信息,请查看 PHP.net 的会话页面

登录页面

<?php
session_start(); 
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "", "", "");
//if post and encryption
if(isset($_POST['Submit'])){
    $userEmail=strip_tags(trim($_POST['userEmail']));
    $userPassword=SHA1(trim($_POST['userPassword']));
    //Check to see if the user left any space empty! For browsers that do not support the HTML5 'required' atribute.
    if($userEmail==""||$userPassword=="") 
        { 
        $error="Please fill in all of the information"; 
        } else {

    if ($stmt = $mysqli->prepare("SELECT userID FROM users WHERE userEmail = ? and userPassword = ? LIMIT 1")) {
        $stmt->bind_param("ss", $userEmail, $userPassword);
        $stmt->execute();
        $stmt->store_result();
        if($stmt->num_rows > 0) {
            $_SESSION['Email'] = $userEmail;
            $stmt->close();
            //go to next page
            header ("location: nextpage.php");    
        }
        $error="Email and Password do not match, please try again."; 
    }
}}
?>
<!DOCTYPE html>
<head>
</head>
<body>
    <!--Display errors-->
<div class="errorbox">
    <?php if(isset($error)){?><strong class="error"><?php echo $error;?></strong><?php } ?>
</div>

登录

                    <form action="#" name="loginform" method="post" >
                    <!--change input type to email if desired but then Spanish accented characters will fail validation -->
                    <label>Email </label>
                    <input type="text" class="styleinput" name="userEmail" maxlength="50" title="Enter Your email" autocomplete="off" placeholder="enter email" required/><br />
                    <label>Password </label>
                    <input type="password" class="styleinput" name="userPassword" maxlength="50" title="Enter Your Password" autocomplete="off" placeholder="enter password" required/>
                    <a href="help.php" class="stylelink"> Forgot your password? </a>
                    <input type="submit" name="Submit" class="stylesubmit" value="Submit">

                    </form>
</body>
</html>

用户必须登录的每隔一个页面

<?php 
session_start(); 
if(!isset($_SESSION['Email'])){
header("location:home.php");
}
?>

您的代码 - 还可以编辑上面的代码以适应您的网站,不要忘记在注册页面上加密密码。