Blogger Information
Blog 43
fans 3
comment 1
visits 30257
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP session+cookie操作+2018年4月23日18时30分
KongLi的博客
Original
783 people have browsed it

使用 SESSION 记录用户登录状态,总共使用四个页面进行,登录页 login.html 、判断页 check.php、用户页 user.php

以及退出页 logout.php 


要保存用户会话首页要在最开始添加,session_start();  且前面不能有其它相关代码,另清除会话需要注意一点,即这串代码

setcookie('PHPSESSID','',time()-3600);  必须清除,否则还会产生PHPSESSID


界面示例:

QQ截图20180423182729.png


相关代码如下:

HTML 部分:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>用户登录</title>
    <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script type="text/javascript" src="js/login.js"></script>
    <style type="text/css">
        .login{
            width: 300px;
            border: 1px solid #3a6c7e;
            border-radius: 20px;
            margin: auto;
        }
        .login h2{
            text-align: center;
        }
        .login p{
            margin-left: 10px;
        }
        .login span{
            margin-left: 15px;
        }
    </style>
</head>
<body>
    <div class="login">
        <h2>用户登录</h2>
        <p>
            <label for="user">账号:</label>
            <input type="text" name="user" id="user">
        </p>
        <p>
            <label for="pass">密码:</label>
            <input type="password" name="pass" id="pass">
        </p>
        <p>
            <label for="record">记住密码</label>
            <input type="checkbox" name="record" id="record" checked>
        </p>
        <p>
            <button>登录</button>
            <!--<span style="color: #AA1111;">密码错误!</span>-->
 </p>
    </div>
</body>
</html>

JS 部分:

$(document).ready(function () {
    //给按钮添加点击事件
    $('button:first').click(function () {
        //得到user pass 关判断是否为空
        if($('#user').val().length==0){
            $('button:first').parent($('span').remove())
            $('button:first').after('<span style="color: #AA1111;">请先输入用户!</span>')
            $('#user').focus()
        }else if($('#pass').val().length==0){
            $('button:first').parent($('span').remove())
            $('button:first').after('<span style="color: #AA1111;">请先输入密码!</span>')
            $('#pass').focus()
        }else {
            $('button:first').parent($('span').remove())

            var record=0
            if($('input[type=checkbox]').prop('checked')){
                record=1
            }

            //使用 Ajax 进行验证
            $.ajax({
                url:'inc/check.php?m=login',
                type:'POST',
                dataType:'JSON',
                data:{
                    'user':$('#user').val(),
                    'pass':$('#pass').val(),
                    'record':record
                },
            success:function (msg,status,xhr) {
                    if(msg['status']==0){
                        // console.log('success')
                        $('button:first').parent($('span').remove())
                        $('button:first').after('<span style="color:#008800">登录成功!正在跳转中...</span>')
                        setTimeout(function () {
                            $(window).attr('location','user.php')
                        },2000)

                    }else if(msg['status']==1){
                        $('button:first').parent($('span').remove())
                        $('button:first').after('<span style="color:#ff0000;">登录密码错误!</span>')
                        setTimeout(function () {
                            $('button:first').parent($('span').remove())
                        },2000)
                    }
                }
            })
        }
    })
})

check.php 部分:

<?php
/医院
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/23
 * Time: 12:52
 */

//开启会话
session_start();

//判断是否存在会话,不存在则进行判断请求
if(!isset($_SESSION['user_id'])) {

    //判断是否登录
    if ($_GET['m'] == 'login') {

        //连接数据库
        $conn = mysqli_connect('localhost', 'root', 'root', 'php') or die('数据库连接失败!');
        //选择数据库
        //mysqli_select_db('php') or die('数据库不存在或不可用');

        //获取用户信息
        $user = $_POST['user'];
        $pass = $_POST['pass'];
        $record = $_POST['record'];

        //拼接SQL查询
        $query = "SELECT `user_id`,`userName` FROM `user` WHERE `userName`='{$user}' AND `userPass`='{$pass}'";

        //执行查询返回结果
        $res = mysqli_query($conn, $query);
        //判断是否存在记录

        //检查查询记录是否为1条
        if (mysqli_num_rows($res) == 1) {

            //是否记住密码
            if ($record == 1) {
                //得到查询中的值
                $row = mysqli_fetch_array($res);
                //设置 session
                $_SESSION['user_id'] = $row['user_id'];
                $_SESSION['userName'] = $row['userName'];

                //设置 cookie 保存时间为1小时
                setcookie('user_id', $row['user_id'], time() + 3600);
                setcookie('userName', $row['userName'], time() + 3600);
            }
                        //登录成功
            echo json_encode([
                'status' => '0',
                'reg_msg' => 'success'
            ]);
        } else {
                //登录失败
            echo json_encode([
                'status' => '1',
                'reg_msg' => 'error'
            ]);
        }


    } else {
        echo json_encode(['msg' => '非法请求!']);
    }

}else{
    //如果存在,则直接跳转页面
    header('Location:user.php');
}

user.php 部分:

<?php
/医院
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/23
 * Time: 16:45
 */

//开启 session
session_start();

//判断是否存在 session 跟 cookie
if(!isset($_SESSION['user_id'])){

    //如果存在 cookie 则用 cookie 给 session 赋值
    if(isset($_COOKIE['user_id']) && isset($_COOKIE['userName'])){
        $_SESSION['user_id']=$_COOKIE['user_id'];
        $_SESSION['userName']=$_COOKIE['userName'];
    }else{
        //跳转页面
        header('Location:login.html');
    }
}

//查检登录状态
if(isset($_SESSION['userName'])){
    echo '当前登录用户:',$_SESSION['userName'];
    echo "<a href='logout.php'>退出</a>";
}

logout.php 部分:

<?php
/医院
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/23
 * Time: 17:19
 */


session_start();

//查找会话
if(isset($_SESSION['user_id'])){

    //删除Cookie
    setcookie('user_id','',time()-3600);
    setcookie('userName','',time()-3600);

    //删除会话
    $_SESSION = [];

    //应用内置session_destroy()函数调用撤销会话
    session_destroy();
    setcookie('PHPSESSID','',time()-3600);
}


//location到初始页面
header('Location:login.html');


Correction status:Uncorrected

Teacher's comments:
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