PHP会话控制实战
COOKIE篇章
首先我们先写案例一个首页(就随便写了一个导航)一个登陆页面一个注册页面
然后我们先整理一下思路
- 首先我们要写好表单,method,action什么的要写好。
- 其次我们要写一个验证脚本用来验证账号密码是否正确,登陆,退出这三个功能。
- 然后就是判断一下是否已经登陆,其实就这么三块。
Login部分(不是重点)
<?php
if (filter_has_var(INPUT_COOKIE, 'user')) {
exit('<script>alert("你已经登入了不要重复登陆噢");location.href="index.php"</script>');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>后台登陆</title>
<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="../css/login.css">
</head>
<body>
<div class="login">
<div class="main">
<div class="logo">
<strong id="logintitle">用户登陆</strong>
</div>
<form action="handle.php?action=login" method="post">
<input type="text" name="username" placeholder="输入用户名" name="username">
<hr class="hr11">
<input type="password" name="password" placeholder="输入密码" name="password">
<hr class="hr11">
<button type="submit" class="btn btn-primary btn-lg btn-block">登陆</button>
<button type="button" class="btn btn-lg btn-block btn-info" onclick="hreftz()">注册</button>
</form>
</div>
</div>
</body>
<script>
function hreftz() {
window.location.href = "register.php";
}
</script>
</html>
验证脚本
验证脚本这一块,用的最多的就是那啥过滤器,filter_input,filter_var照着手册边查边打,自然而然就记住了,并且养成写注释的习惯<?php
$users = [
[
'id' => 1,
'name' => 'admin',
'email' => 'admin@php.cn',
'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
],
[
'id' => 2,
'name' => 'peter',
'email' => 'peter@php.cn',
'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
],
];
//获取来源链接
$urlcheck = filter_input(INPUT_SERVER, 'HTTP_REFERER');
$saferules = [
'login.php',
'index.php',
'register.php'
];
$url = basename($urlcheck);
if (!in_array($url, $saferules)) {
exit('非法来源,拒绝访问!');
}
$action = filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
switch ($action) {
//登陆模块
case 'login':
//检查数据来源是否合法
if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') {
//获取邮箱
$username = filter_var(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING), FILTER_VALIDATE_EMAIL);
//获取密码
$password = sha1(filter_input(INPUT_POST, 'password'));
//接下来与数组进行验证
$res = array_filter($users, function ($users) use ($username, $password) {
return $username === $users['email'] && $password === $users['password'];
});
//如果$res的值是true那就是账号密码验证通过了
if (count($res) === 1) {
setcookie('user', serialize(array_pop($res)));
exit('<script>alert("登陆成功");location.href="index.php"</script>');
} else {
exit('<script>alert("账号或者密码不正确");location.href="index.php"</script>');
}
} else {
exit('提交数据非法');
}
break;
case 'register':
//通过过滤器获取用户名
$name =filter_var(filter_input(INPUT_POST,'name'),FILTER_SANITIZE_SPECIAL_CHARS);
//获取邮箱
$email = filter_var(filter_input(INPUT_POST,'email',FILTER_SANITIZE_STRING),FILTER_VALIDATE_EMAIL);
$password = sha1(filter_input(INPUT_POST,'p1'));
$password1 = sha1(filter_input(INPUT_POST,'p2'));
if ($password !== $password1) {
exit('<script>alert("第一次密码输入与第二次密码输入不同");location.href="register.php"</script>');
}
$id=3;
//接下来判断OK了之后应该写入数据库
$data = compact('id','name','email','password');
//方法一:如下; 方法二:直接 $users[]=$data;
if(array_push($users,$data)){
exit('<script>alert("注册成功");location.href="login.php"</script>');
}
break;
case 'logout':
if (filter_input(INPUT_COOKIE, 'user')) {
setcookie('user', null, time() - 3600);
exit('<script>alert("退出成功");location.href="index.php"</script>');
}
break;
}
一般来说cookie的过期时间可以这样子设置time()-3600
Index.php页面就写个判断登陆获取一下用户名
顺便提一句这里的<?php
//判断是否已经登陆
if (filter_has_var(INPUT_COOKIE, 'user')) {
$user = unserialize(filter_input(INPUT_COOKIE, 'user'));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
nav {
height: 35px;
width: 100%;
padding: 0 20px;
box-sizing: border-box;
background: black;
display: flex;
justify-content: space-between;
}
nav>a {
line-height: 35px;
text-decoration: none;
color: white;
}
</style>
</head>
<body>
<nav>
<a href="">LOGO</a>
<?php if (isset($user)) : ?>
<a href="" id="logout">
<span><?php echo $user['name'] ?></span>
退出
</a>
<?php else : ?>
<a href="login.php">登陆</a>
<?php endif ?>
</nav>
<script>
// 为退出按钮创建事件监听器
if (document.querySelector('#logout') !== null) {
document.querySelector('#logout').addEventListener('click', function(event) {
if (confirm('是否退出')) {
// 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
event.preventDefault();
// 跳转到退出事件处理器
window.location.assign('handle.php?action=logout');
}
});
}
</script>
</body>
</html>
querySelector
和getElementBy
是有区别的querySelector
是根据CSS选择器来的register.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>后台登陆</title>
<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="../css/login.css">
</head>
<body>
<div class="login">
<div class="main">
<div class="logo">
<strong id="logintitle">用户注册</strong>
</div>
<form action="handle.php?action=register" onsubmit="return compare()" method="post">
<input type="text" placeholder="用户名" name="name">
<hr class="hr11">
<input type="text" placeholder="邮箱" name="email">
<hr class="hr11">
<input type="password" placeholder="密码" id="p1" name="password">
<hr class="hr11">
<input type="password" placeholder="重复密码" id="p2" name="password">
<hr class="hr11">
<button type="submit" class="btn btn-lg btn-block btn-info">注册</button>
<span id="tips" style="color: red"></span>
</form>
</div>
</div>
<script>
// 验证二次密码是否相等?
function compare() {
if (document.forms[0].p1.value.trim() !== document.forms[0].p2.value.trim()) {
document.querySelector('#tips').innerText = '二次密码不相等';
return false;
}
}
</script>
</body>
</html>
Session
Session最重要的其实是开启sessionsession_start
什么页面要用什么页面就要开启验证脚本
<?php
session_start();
$users = [
[
'id' => 1,
'name' => 'admin',
'email' => 'admin@php.cn',
'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
],
[
'id' => 2,
'name' => 'peter',
'email' => 'peter@php.cn',
'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
],
];
//获取来源链接
$urlcheck = filter_input(INPUT_SERVER, 'HTTP_REFERER');
$saferules = [
'login.php',
'index.php',
'register.php'
];
$url = basename($urlcheck);
if (!in_array($url, $saferules)) {
exit('非法来源,拒绝访问!');
}
$action = filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
switch ($action) {
//登陆模块
case 'login':
//检查数据来源是否合法
if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') {
//获取邮箱
$username = filter_var(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING), FILTER_VALIDATE_EMAIL);
//获取密码
$password = sha1(filter_input(INPUT_POST, 'password'));
//接下来与数组进行验证
$res = array_filter($users, function ($users) use ($username, $password) {
return $username === $users['email'] && $password === $users['password'];
});
//如果$res的值是true那就是账号密码验证通过了
if (count($res) === 1) {
$_SESSION['user'] = serialize(array_pop($res));
exit('<script>alert("登陆成功");location.href="index.php"</script>');
} else {
exit('<script>alert("账号或者密码不正确");location.href="index.php"</script>');
}
} else {
exit('提交数据非法');
}
break;
case 'register':
//通过过滤器获取用户名
$name = filter_var(filter_input(INPUT_POST, 'name'), FILTER_SANITIZE_SPECIAL_CHARS);
//获取邮箱
$email = filter_var(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING), FILTER_VALIDATE_EMAIL);
$password = sha1(filter_input(INPUT_POST, 'p1'));
$password1 = sha1(filter_input(INPUT_POST, 'p2'));
if ($password !== $password1) {
exit('<script>alert("第一次密码输入与第二次密码输入不同");location.href="register.php"</script>');
}
$id = 3;
//接下来判断OK了之后应该写入数据库
$data = compact('id', 'name', 'email', 'password');
//方法一:如下; 方法二:直接 $users[]=$data;
if (array_push($users, $data)) {
exit('<script>alert("注册成功");location.href="login.php"</script>');
}
break;
case 'logout':
if (isset($_SESSION['user'])) {
session_destroy();
exit('<script>alert("退出成功");location.href="index.php"</script>');
}
break;
}
Index.php核心代码
session_start();
//判断是否已经登陆
if (isset($_SESSION['user'])) {
$user = unserialize($_SESSION['user']);
}
Login.php
因为PHP没有关于SESSION的过滤器所以我们直接用isset就完事了if (isset($_SESSION['user'])) {
exit('<script>alert("你已经登入了不要重复登陆噢");location.href="index.php"</script>');
}
接下来是SESSION和COOKIE的理解图