1. 会话控制
- HTTP 是基于无连接的网络协议, 每一次访问, 对于服务器来说, 都是全新的
- 如果记住访问者,以及记录连接状态, 可以提升用户体验,完成许多个性化的功能
- 例如, 用户登录, 购物车等
- 其实让服务器记住用户的方式很简单, 就和生活中, 我们办会员卡是一样的
- 会员卡的存储位置有二个地方, 要么放在你身上, 要么保存到商家电脑中
- 所以, 网络中的用户资料也会保存在二个地方: 浏览器(客户端)和服务器中
- 保存到浏览器中的叫:
cookie
- 保存到服务器中的叫:
session
2. COOKIE
- 保存在客户端
- 变量:
$_COOKIE
- 变量过滤器:
filter_input(INPUT_COOKIE, key)
- 设置使用专用函数:
setcookie(名称, 值, 过期时间)
- 生效需要分二步完成: 先下达指令到浏览器, 再由浏览器完成 cookie 写入
3. SESSION
- 保存在服务器端
- 变量:
$_SESSION
- 变量过滤器:
filter_input(INPUT_SESSION, key)
- 设置使用专用函数:
setcookie(名称, 值, 过期时间)
- 生效需要分二步完成: 先下达指令到浏览器, 再由浏览器完成 cookie 写入
4.演示代码
主页部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/index.css" />
<title>糗事百科</title>
</head>
<body>
<header>
<nav>
<a href="">
<img src="https://i.loli.net/2020/05/10/4yafTolzCbOnqiU.png" alt="" />
</a>
</nav>
<nav>
<a href="index.php">首页</a>
<a href="">推荐</a>
<a href="">图文</a>
<a href="">视频</a>
<a href="">论坛</a>
</nav>
<nav>
<?php
#####
// 如果是session
// 开启会话
// session_start();
// if (isset($_SESSION['user'])){
// $session = unserialize($_SESSION['user']);
// echo <<< AAA
//<a href = "">欢迎你!{$session['username']} <img
// src="https://pic.qiushibaike.com/system/avtnew/648/6480555/thumb/20200201071150.jpg"
// alt=""
// /></a>
//<a href="" id="logout">退出</a>
#####
//判断是否登陆成功
if (isset($_COOKIE['user'])){
$cookie = unserialize($_COOKIE['user']);
echo <<< AAA
<a href = "">欢迎你!{$cookie['username']} <img
src="https://pic.qiushibaike.com/system/avtnew/648/6480555/thumb/20200201071150.jpg"
alt=""
/></a>
<a href="" id="logout">退出</a>
AAA;
}else{
echo <<< BBB
<a href="login.php">登录</a>
<a href="register.php">注册</a>
BBB;
}
?>
</nav>
</header>
<main>
<section>
<div>
<img
src="https://pic.qiushibaike.com/system/avtnew/648/6480555/thumb/20200201071150.jpg"
alt=""
/><span>旧梦雨伞</span>
</div>
<div>
有天晚上,和同事出去喝酒,先是用小酒杯,喝了几杯觉得不过瘾,
就叫老板拿大碗来,满满倒了一大碗,和同事一碰杯,一口干了。。
那次我醉得很厉害,一直到第二天下午才醒过来,还觉得晕头转向的,上厕所都是扶着墙去的!
同事来看我时,我看到同事两只眼睛都是乌黑的,吃了一惊:被谁揍了啊?告诉我,我帮你报
仇! 同事说:被你打的!你揍自己吧!!
我不信。同事说:你闹着要去找你前女友,我不让你去,所以……你不会真的一点印象都没有吧?
我。。。特么的,我咋一点都想不起来呢??
</div>
<div class="item1">
<div>
<a href="">好笑</a>
<a href="">太low</a>
<a href="">评论</a>
</div>
<div>
分享到
<a href="">qq</a>
<a href="">微信</a>
<a href="">微博</a>
</div>
</div>
<div>
神评
<div>
,我不让你去,所以……你不会真的一点印象都没有吧?
我。。。特么的,我咋一点都想不起来呢??
</div>
</div>
<hr />
</section>
<section>
<div>
<img
src="https://pic.qiushibaike.com/system/avtnew/648/6480555/thumb/20200201071150.jpg"
alt=""
/><span>旧梦雨伞</span>
</div>
<div>
有天晚上,和同事出去喝酒,先是用小酒杯,喝了几杯觉得不过瘾,
就叫老板拿大碗来,满满倒了一大碗,和同事一碰杯,一口干了。。
那次我醉得很厉害,一直到第二天下午才醒过来,还觉得晕头转向的,上厕所都是扶着墙去的!
同事来看我时,我看到同事两只眼睛都是乌黑的,吃了一惊:被谁揍了啊?告诉我,我帮你报
仇! 同事说:被你打的!你揍自己吧!!
我不信。同事说:你闹着要去找你前女友,我不让你去,所以……你不会真的一点印象都没有吧?
我。。。特么的,我咋一点都想不起来呢??
</div>
<div class="item1">
<div>
<a href="">好笑</a>
<a href="">太low</a>
<a href="">评论</a>
</div>
<div>
分享到
<a href="">qq</a>
<a href="">微信</a>
<a href="">微博</a>
</div>
</div>
<div>
神评
<div>
,我不让你去,所以……你不会真的一点印象都没有吧?
我。。。特么的,我咋一点都想不起来呢??
</div>
</div>
</section>
</main>
<script>
// 退出按钮监听
document.querySelector('#logout').addEventListener('click',function (event) {
if (confirm('是否退出')){
// 禁用a跳转
event.preventDefault();
window.location.assign('handle.php?action=logout');
}
})
</script>
</body>
</html>
处理器部分
<?php
#####
//如果是session
//开启会话
//session_start();
#####
//先连接数据库
$pdo = new PDO('mysql:host=localhost;dbname=php11.edu', 'php11.edu', 'php11.edu');
$stmt = $pdo->prepare('SELECT * FROM `qb_users`');
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
//处理用户登录
@$action = $_GET['action'];
if (@isset($action)) {
switch (strtolower($action)) {
// 登录
case 'login':
// 先判断请求是否合法
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 开始验证
// 获取需要验证的数据
$email = $_POST['email'];
$password = sha1($_POST['password']);
$results = array_filter($users, function ($user) use ($email, $password) {
return $user['email'] === $email && $user['password'] === $password;
});
if (count($results) === 1) {
#####
//如果是session
//$_SESSION['user'] = serialize(array_pop($results));
#####
setcookie('user', serialize(array_pop($results)));
die('<script> alert("登录成功");location.href="index.php"</script>');
} else {
die('<script> alert("账号或密码错误");location.href="login.php"</script>');
}
} else {
die('请求非法');
}
break;
// 退出
case 'logout':
if (isset($_COOKIE['user'])) {
setcookie('user', null, time() - 3600);
die('<script>alert("退出成功"); location.assign("index.php")</script>');
}
#####
//如果是session
// if (isset($_SESSION['username'])) {
// session_destroy();
// die('<script>alert("退出成功"); location.assign("index.php")</script>');
// }
#####
break;
//// 注册
case 'register':
/* @var string $username
* @var string $p1
* @var string $email
* */
extract($_POST);
$p1 = sha1($p1);
$register_time = time();
//// 先检测一下数据库中有没有该邮箱如果有提示该邮箱已经注册
$atmt = $pdo->prepare("SELECT `email` FROM `qb_users` WHERE `email` = '{$email}' ");
$atmt->execute();
$arr = $atmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($arr) === true) {
// 如果是空则创建插入数据库
$sql = "INSERT `qb_users` SET `username`='{$username}',`password` = '{$p1}',`email`='{$email}',`register_time` = '{$register_time}'";
$stmt = $pdo->prepare($sql);
$stmt->execute();
// 检测一下
if ($stmt->rowCount() === 1) {
// 注册成功后创建cookie
// 先查询到该条数据
$stmt = $pdo->prepare('SELECT * FROM `qb_users`');
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
$results = array_filter($users, function ($user) use ($email, $p1) {
return $user['email'] === $email && $user['password'] === $p1;
});
// 序列化cookie返回
//#####
//如果是session
//$_SESSION['user'] = serialize(array_pop($results));
#####
setcookie('user', serialize(array_pop($results)));
die('<script>alert("注册成功!");location.assign("index.php")</script>');
} else {
die('<script>alert("注册失败!");location.assign("register.php")</script>');
}
} else {
die('<script>alert("该邮箱已经注册过了,请直接登录");location.assign("login.php")</script>');
}
break;
default:
die('非法的操作');
}
}else{
echo '请求非法';
}
登录部分
<?php
//判断一下是否已经登陆
if (isset($_COOKIE['user'])){
die('<script>alert("请不要重复登录");location.href="index.php";</script>');
}
//如果是session
//先开启会话
//session_start();
//if (isset($_SESSION['user'])){
// die('<script>alert("请不要重复登录");location.href="index.php";</script>');
//}
//?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/style.css" />
<title>用户登录</title>
</head>
<body>
<main>
<form action="handle.php?action=login" method="POST">
<h3>用户登录</h3>
<div>
<label for="username">邮箱:</label>
<input
type="email"
id="email"
name="email"
placeholder="请输入邮箱地址"
required
/>
</div>
<div>
<label for="password">密码:</label>
<input
type="password"
id="password"
name="password"
placeholder="请输入密码"
minlength="8"
required
/>
</div>
<button>登录</button>
<a href="register.php"><div>没有账号?点击注册</div> </a>
</form>
</main>
</body>
</html>
注册部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="css/style.css" />
<title>用户注册</title>
</head>
<body>
<main>
<form action="handle.php?action=register" method="post" onsubmit="return compare()">
<h3>用户注册</h3>
<div>
<label for="username">昵称:</label>
<input
type="text"
id="username"
name="username"
placeholder="请输入4-8位昵称"
maxlength="8"
required
autofocus
/>
</div>
<div>
<label for="email">邮箱:</label>
<input
type="email"
id="email"
name="email"
placeholder="请输入邮箱地址"
required
autofocus
/>
</div>
<div>
<label for="p1">密码:</label>
<input
type="password"
id="p1"
name="p1"
placeholder="请输入8-16位密码"
minlength="8"
maxlength="16"
required
/>
</div>
<div>
<label for="p2">重复:</label>
<input
type="password"
id="p2"
name="p2"
placeholder="重复输入密码"
minlength="8"
maxlength="16"
required
/>
</div>
<button>注册</button><span id="tips"></span>
<a href="login.php">
<div>已有账号?去登录</div>
</a>
</form>
</main>
<script>
function compare() {
if (document.forms[0].p1.value.trim() !== document.forms[0].p2.value.trim()){
alert('二次密码不相等');
return false;
}
}
</script>
</body>
</html>
index.css
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
body {
min-width: 900px;
}
header {
background-color: lightskyblue;
display: flex;
justify-content: space-around;
align-items: center;
}
header > nav:first-child {
height: 40px;
}
header > nav:first-of-type img {
height: 100%;
}
header > nav:last-of-type img {
border: none;
height: 30px;
border-radius: 50%;
}
header > nav > a {
text-decoration: none;
color: aliceblue;
margin: 0px 20px;
}
header > nav > a:hover {
color: lightcoral;
}
main {
width: 50vw;
margin: auto;
display: flex;
flex-flow: column nowrap;
}
main > section {
margin-top: 15px;
}
main > section > div:first-of-type {
height: 30px;
display: flex;
align-items: center;
}
main > section > div:first-of-type > img {
height: 100%;
border: none;
border-radius: 50%;
margin-right: 15px;
}
main > section > div:first-of-type > span {
font-size: 0.8rem;
color: slategray;
}
main > section > div:nth-of-type(2) {
margin-top: 10px;
text-indent: 20px;
line-height: 20px;
font-size: 0.9rem;
color: saddlebrown;
}
.item1 {
margin: 15px 0px;
display: flex;
justify-content: space-between;
}
.item1 a {
padding: 2px 8px;
text-decoration: none;
background-color: lightblue;
border: none;
border-radius: 5px;
font-size: 0.8rem;
}
.item1 > div:last-of-type {
font-size: 0.8rem;
color: violet;
}
section > div:last-of-type {
color: red;
display: flex;
margin-bottom: 20px;
}
section > div:last-of-type div {
padding: 3px 5px;
margin-left: 10px;
width: 80%;
border: 1px solid lavender;
color: chocolate;
font-size: 0.8rem;
}
hr {
color: lightcyan;
}
style.css
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
body {
background-color: lightcyan;
}
main {
margin: 100px auto;
width: 300px;
padding: 20px;
border: none;
border-radius: 20px;
background-color: lightskyblue;
text-align: center;
}
main div {
margin: 15px 0px;
}
button {
padding: 5px 30px;
width: 100px;
border: none;
border-radius: 10px;
}
button:hover {
background-color: lightgreen;
}
a {
text-decoration: none;
font-size: 0.8rem;
color: crimson;
}
a:hover {
color: aliceblue;
}
总结
没学会话控制之前感觉这个一定很难,学会之后发现简直不要太简单!