博客列表 >使用PHP Session实现登录身份认证

使用PHP Session实现登录身份认证

叫我孙大树
叫我孙大树原创
2022年08月23日 05:53:32334浏览

介绍下所创建项目的目录结构:

该项目共包含一个名为0822的文件夹,文件夹内有四个文件,文件名分别为:home.php;login.php;reginster.php;userData.json。

该项目实现了用户的登录,验证,注册与登出的完整过程。

注:所有代码保留debug过程。一切美好绝不是简简单单或信手拈来~

注:为了美观些,项目引入了Layui。

注:因个人原因,使用json文件代替了数据库。

下面为每个文件的详细代码:

login.php

<?php
session_start();
if (isset($_SESSION['username']) &&  isset($_SESSION['password'])){
    echo '您已登陆';
    header("refresh:2;url=home.php");
    exit();
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
    <link href="//unpkg.com/layui@2.7.6/dist/css/layui.css" rel="stylesheet">
    <script src="//unpkg.com/layui@2.7.6/dist/layui.js"></script>
    <style>
        .box {
            margin-top: 40px;
        }

        .right {
            float: right;
        }

        .bbbbb{
            text-align: center;
            display: block;
        }
    </style>
</head>
<body>


<div class="layui-container box">
    <div class="layui-row">
        <div class="layui-col-md12">
            <h1 style="margin-bottom: 15px;text-align: center;font-size: 80px">用户登录</h1>
            <form class="layui-form" method="post" action="home.php">
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名"
                               autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码框</label>
                    <div class="layui-input-inline">
                        <input type="password" name="password" required lay-verify="required" placeholder="请输入密码"
                               autocomplete="off" class="layui-input">
                    </div>
                    <div class="layui-form-mid layui-word-aux">默认密码是123456</div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="formDemo">登录</button>
                    </div>
                </div>
            </form>
            <div class="layui-input-inline bbbbb">
                <button class="layui-btn" onclick="window.location = 'reginster.php'" >没有账号?点我去注册</button>
            </div>
        </div>
    </div>
</div>

</body>
</html>
<script>
    //Demo
    layui.use('form', function () {
        var form = layui.form;
        var $ = layui.jquery;
        // $("form").bind("submit",function (e){
        //     e.preventDefault();
        // })

        //提交
        // form.on('submit(formDemo)', function (data) {
        //     layer.msg(JSON.stringify(data.field));
        //     let ddata = JSON.stringify(data.field);
        //     // let HTTP = new XMLHttpRequest();
        //     // HTTP.open('POST','./login.php')
        //     // $.post('home.php',JSON.stringify(data.field),function (data,status){
        //     //     window.location = 'home.php'
        //     // })
        //     // return false;
        //     $.post("home.php",ddata,function(data,status){
        //         console.log(data);
        //         console.log(status);
        //         // window.location = 'home.php'
        //     })
        // });
        // form.submit('submit(formDemo)',function (data){
        //     console.log(data)
        // })
    });
</script>

home.php

<?php
session_start();
//print_r($_GET);

if ($_GET['logout'] == 1) {
    session_destroy();
    echo '您已登出';
    header("refresh:2;url=login.php");
    exit();
}

$userData = file_get_contents(__DIR__ . '/userData.json');
$userData = json_decode($userData, true);

$_POST['username'] = trim($_POST['username']);
$_POST['password'] = trim($_POST['password']);
//print_r($userData);
foreach ($userData as $key => $value) {
    if ($_POST == $value) {
        $_SESSION['username'] = $value['username'];
        $_SESSION['password'] = $value['password'];
    }
//    else{
//        session_destroy();
//        echo '用户名或密码不正确';
//        header("refresh:2;url=login.php");
//        exit();
//    }
}
//var_dump(isset($_SESSION['username']));

if (!isset($_SESSION['username'])) {
    session_destroy();
    echo '用户名或密码不正确';
    header("refresh:2;url=login.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>用户主页</title>
    <link href="//unpkg.com/layui@2.7.6/dist/css/layui.css" rel="stylesheet">
    <script src="//unpkg.com/layui@2.7.6/dist/layui.js"></script>
    <style>
        .box {
            margin-top: 40px;
        }

        .right {
            float: right;
        }
    </style>
</head>
<body>
<ul class="layui-nav">
    <li class="layui-nav-item">
        <a>孙大树的用户状态管理完整解决方案</a>
    </li>

    <li class="layui-nav-item right">
        <a href=""><img src="//t.cn/RCzsdCq" class="layui-nav-img">您好:<?= $_SESSION['username'] ?></a>
        <dl class="layui-nav-child">
            <dd><a href="home.php?logout=1">退出</a></dd>
        </dl>
    </li>


</ul>
<h1 style="text-align: center;margin-top: 50px">当前登录用户为:<?= $_SESSION['username'] ?></h1>
</body>
</html>

reginster.php

<?php
$userData = file_get_contents(__DIR__ . '/userData.json');
$userData = json_decode($userData, true);
//$userData = array_push($userData,$_POST);
$userData[] = $_POST;
if (!empty($_POST)) {
    if (file_put_contents(__DIR__ . '/userData.json', json_encode($userData))) {
        echo '写入成功';
    }

} else {
    if (!empty($_POST)) {
        echo '写入失败';
    }
}
//print_r($userData)
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>用户注册</title>
    <link href="//unpkg.com/layui@2.7.6/dist/css/layui.css" rel="stylesheet">
    <script src="//unpkg.com/layui@2.7.6/dist/layui.js"></script>
    <style>
        .box {
            margin-top: 40px;
        }

        .right {
            float: right;
        }
    </style>
</head>
<body>


<div class="layui-container box">
    <div class="layui-row">
        <div class="layui-col-md12">
            <h1 style="margin-bottom: 15px;text-align: center;font-size: 80px">用户注册</h1>
            <form class="layui-form" method="post" action="reginster.php">
                <div class="layui-form-item">
                    <label class="layui-form-label">用户名</label>
                    <div class="layui-input-block">
                        <input type="text" name="username" required lay-verify="required" placeholder="请输入用户名"
                               autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">密码框</label>
                    <div class="layui-input-block">
                        <input type="password" name="password" required lay-verify="required" placeholder="请输入密码"
                               autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit lay-filter="formDemo">注册</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
</body>
</html>
<script>
    //Demo
    layui.use('form', function () {
        var form = layui.form;
        var $ = layui.jquery;
    });
</script>

userData.json

[
    {
        "username": "admin",
        "password": "123456"
    },
    {
        "username": "admin2",
        "password": "123456"
    }
]

最终效果如下:1661204867675445.jpg

登录后界面.jpg

用户注册.jpg

错误处理:

密码错误或防盗链.jpg

登出.jpg

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议