Blogger Information
Blog 33
fans 0
comment 2
visits 41921
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP 使用Cookie及Session实现登录状态保存
hanyufeng的博客
Original
1178 people have browsed it

说明:

使用cookie及session保存用户登录信息

运行效果:

登录页面 login.php

L31-1.png

后台页面admin.php

L31-2.png

示例源码:

login.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--本地引用-->
 <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="jquery-3.2.1.min.js"></script>
    <script src="bootstrap-3.3.7-dist/js/bootstrap.js"></script>
    <!--CDN/远程引用-->
    <!--<link rel="stylesheet" href="http://apps.bdimg.com/libs/bootstrap/3.3.4/css/bootstrap.css">-->
    <!--<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>-->
    <!--<script src="http://apps.bdimg.com/libs/bootstrap/3.3.4/js/bootstrap.js"></script>-->
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h3>登录</h3>
            <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
                <div class="form-group">
                    <label for="userName">用户名</label>
                    <input type="text" class="form-control" name="userName" id="userName" placeholder="用户名" value="<?php echo  isset($_POST['userName'])?$_POST['userName']:''; ?>">
                </div>
                <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" class="form-control" name="password" id="password" placeholder="密码" value="<?php echo isset($_POST['password'])?$_POST['password']:''; ?>">
                </div>
                <button type="submit" class="btn btn-primary">登录</button>
            </form>
        </div>
    </div>

</div>

</body>
</html>

<?php
//连接数据库
require 'inc/connect.php';
//用户登录验证
if ($_SERVER['REQUEST_METHOD'] ==  'POST') {
    //初始化
 $userName = '';
 $password = '';
 //1、前端验证
 if (empty($_POST['userName'])) { //用户名是否为空
 echo '<script>alert("用户名不能为空~~")</script>';
 } else {  //去掉左右空格并将html字符转义为实体
 $userName = htmlspecialchars(trim($_POST['userName']));
 }

    if (empty($_POST['password'])) {
        echo '<script>alert("密码不能为空~~");</script>';
 } else {  //去掉左右空格并将html字符转义为实体
 $password = htmlspecialchars(trim($_POST['password']));
 }

    if ($userName && $password) {
        //2、后端的数据库验证
 try{
            $sql = "SELECT `name`,`password` FROM user WHERE name=:name AND password=sha1(:password)";
 $pdoStmt = $pdo->prepare($sql);
 $pdoStmt->bindParam(':name',$userName,PDO::PARAM_STR);
 $pdoStmt->bindParam(':password',$password,PDO::PARAM_STR);
 $res = $pdoStmt->execute();
 if (true == $res) {
                if ($pdoStmt->rowCount() === 1) {
                    //如果验证通过,把用户信息写入cookie
 setcookie('userName', $userName,time()+60*60,'/L31/');
 setcookie('password', $password,time()+60*60,'/L31/');
 echo '<script>alert("登录成功~~");location.href="admin.php"</script>';
 } else {
                    echo '<script>alert("用户名或密码错误,请重新输入~~");history.back()</script>';
 }
            } else {
                print_r($pdoStmt->errorInfo());
 }

        }catch (PDOException $e) {
            echo $e->getMessage();
 die('数据库连接失败,强制退出~~');
 }
    } else {
        echo '<script>alert("输入有误,请检查~~")</script>';
 }

}
?>

admin.php

<?php
echo '<h2>PHP中文网管理后台</h2>';
if (isset($_COOKIE['userName'])) { //判断当前用户是否登录?
    echo '<p>欢迎管理员:<span style="color:red">'.$_COOKIE['userName'].'</span></p>';
} else {
    echo '<script>alert("请登录~~");location.href="login.php"</script>';
}

以上使用的是cookie,改为session需要修改:

login.php 第71、72行

$_SESSION['userName'] = $userName;
$_SESSION['password'] = $password;

admin.php

<?php
echo '<h2>PHP中文网管理后台</h2>';
if (isset($_SESSION['userName'])) { //判断当前用户是否登录?
    echo '<p>欢迎管理员:<span style="color:red">'.$_SESSION['userName'].'</span></p>';
} else {
    echo '<script>alert("请登录~~");location.href="login.php"</script>';
}

cookie 和 session的区别:

cookie机制是在客户端保持登录状态,而session机制是在服务器端保存。

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!