Blogger Information
Blog 29
fans 0
comment 0
visits 19488
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
完整的登录验证案例(cookie/session)分别实现-2019年7月26日
blog
Original
754 people have browsed it

登录功能如下图

登录与验证.png

实现上述功能大致分为5个php文件

check.php:

登录处理

dispatch.php:

请求派发器,通过其他文件<a>标签href进行dispatch.php?action=xxx;的写法,获取action的值并对值相对应的动作进行派发处理,并调用不同的脚本进行响应

index.php:

主页面

login.php:

登录页面

logout.php:

退出,销毁cookie/session

数据库连接

database.php

实例

<?php

return [
        'type' => 'mysql',
        'host' => '127.0.0.1',
        'dbname' => 'php',
        'username' => 'root',
        'password' => 'root'
    ];

运行实例 »

点击 "运行实例" 按钮查看在线实例

connect.php

实例

<?php
$db = require 'database.php';
// $dsn
$dsn = "{$db['type']}:host={$db['host']};dbname={$db['dbname']}";
$username = $db['username'];
$password = $db['password'];
try {
    $pdo = new PDO($dsn, $username, $password);
//    var_dump($pdo);
} catch (PDOException $e) {
    die('连接失败' . $e->getMessage());
}

运行实例 »

点击 "运行实例" 按钮查看在线实例



一.cookie实现

check.php:

实例

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST['email'];
    $password = sha1($_POST['password']);
    $sql = 'SELECT * FROM `user` WHERE `email` = :email AND `password` = :password LIMIT 1';
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['email'=>$email, 'password'=>$password]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (false === $user) {
        echo '<script>alert("验证失败");history.back();</script>';
        die;
    }
    setcookie('username', $user['username']);
    echo '<script>alert("登录成功");location.assign("index.php");</script>';
    exit;
} else {
    die('请求类型错误');
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

dispatch.php:

实例

<?php
//请求派发器
require __DIR__.'/inc/connect.php';
$action = isset($_GET['action']) ? $_GET['action'] : 'login';
//strtolower 转换小写  trim 去掉空格   htmlentities 转换特殊字符
$action=htmlentities(strtolower(trim($action)));
//请求分发
switch($action){
    case 'login':
        require __DIR__.'/login.php';
        break;
        //验证登录
    case 'check':
        require __DIR__.'/check.php';
        break;
        //退出登录
    case 'logout':
        require __DIR__.'/logout.php';
        break;
    default:
        echo '<script>location.assign("index.php");</script>';

}

运行实例 »

点击 "运行实例" 按钮查看在线实例

index.php:

实例

<?php
if(isset($_COOKIE['username'])&&$_COOKIE['username']==='admin'){
    echo "用户: ".$_COOKIE['username']."已登录<br>";
    echo "<a href='dispatch.php?action=logout'>退出</a>";
}else{
    echo "<a href='dispatch.php?action=login'>请登录</a>";
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

login.php:

实例

<?php
//防止用户重复登录
if (isset($_COOKIE['username']) && $_COOKIE['username'] === 'admin') {
    echo '<script>alert("不要重复登录");location.assign("index.php");</script>';
}
?>
<!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>
</head>
<body>
<h3>用户登录</h3>
<form action="dispatch.php?action=check" method="post" onsubmit="return isEmpty();">
    <p>
        <label for="email">邮箱:</label>
        <input type="email" name="email" id="email">
    </p>

    <p>
        <label for="password">密码:</label>
        <input type="password" name="password" id="password">
    </p>

    <p>
        <button>提交</button>
    </p>
</form>
<script>
    function isEmpty() {
        var email = document.getElementById('email').value;
        var password = document.getElementById('password').value;

        if (email.length=== 0 || password.length===0) {
            alert('邮箱和密码不能为空');
            return false;
        }
    }
</script>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例

logout.php:

实例

<?php

if(isset($_COOKIE['username'])&&$_COOKIE['username']==='admin'){
    setcookie('username',null,time()-3600);
    echo '<script>alert("退出成功");location.assign("index.php");</script>';
}else{
    echo '<script>alert("请先登录");location.assign("login.php");</script>';
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

1.png

二.session实现

check.php:

实例

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST['email'];
    $password = sha1($_POST['password']);
    $sql = 'SELECT * FROM `user` WHERE `email` = :email AND `password` = :password LIMIT 1';
    $stmt = $pdo->prepare($sql);
    $stmt->execute(['email'=>$email, 'password'=>$password]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if (false === $user) {
        echo '<script>alert("验证失败");history.back();</script>';
        die;
    }
    setcookie('username', $user['username']);
    echo '<script>alert("登录成功");location.assign("index.php");</script>';
    exit;
} else {
    die('请求类型错误');
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

dispatch.php:

实例

<?php
//请求派发器
require __DIR__.'/inc/connect.php';
$action = isset($_GET['action']) ? $_GET['action'] : 'login';
//strtolower 转换小写  trim 去掉空格   htmlentities 转换特殊字符
$action=htmlentities(strtolower(trim($action)));
//请求分发
switch($action){
    case 'login':
        require __DIR__.'/login.php';
        break;
        //验证登录
    case 'check':
        require __DIR__.'/check.php';
        break;
        //退出登录
    case 'logout':
        require __DIR__.'/logout.php';
        break;
    default:
        echo '<script>location.assign("index.php");</script>';

}

运行实例 »

点击 "运行实例" 按钮查看在线实例

index.php:

实例

<?php
if(isset($_COOKIE['username'])&&$_COOKIE['username']==='admin'){
    echo "用户: ".$_COOKIE['username']."已登录<br>";
    echo "<a href='dispatch.php?action=logout'>退出</a>";
}else{
    echo "<a href='dispatch.php?action=login'>请登录</a>";
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

login.php:

实例

<?php
//防止用户重复登录
if (isset($_COOKIE['username']) && $_COOKIE['username'] === 'admin') {
    echo '<script>alert("不要重复登录");location.assign("index.php");</script>';
}
?>
<!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>
</head>
<body>
<h3>用户登录</h3>
<form action="dispatch.php?action=check" method="post" onsubmit="return isEmpty();">
    <p>
        <label for="email">邮箱:</label>
        <input type="email" name="email" id="email">
    </p>

    <p>
        <label for="password">密码:</label>
        <input type="password" name="password" id="password">
    </p>

    <p>
        <button>提交</button>
    </p>
</form>
<script>
    function isEmpty() {
        var email = document.getElementById('email').value;
        var password = document.getElementById('password').value;

        if (email.length=== 0 || password.length===0) {
            alert('邮箱和密码不能为空');
            return false;
        }
    }
</script>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例

logout.php:

实例

<?php

if(isset($_COOKIE['username'])&&$_COOKIE['username']==='admin'){
    setcookie('username',null,time()-3600);
    echo '<script>alert("退出成功");location.assign("index.php");</script>';
}else{
    echo '<script>alert("请先登录");location.assign("login.php");</script>';
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

1.png


Correction status:qualified

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!