PHP会话控制实战cookie、session
COOKIE
1、数据保存在客户端浏览器上,如果浏览器关闭cookie,则无法使用
2、创建cookie:setcookie(名称,值,[过期时间])
3、使用cookie:$_COOKIE['名称']
4、删除cookie:为cookie设置一个已经过期的时间,如:setcookie(名称,值,time()-1)
1.index
<?php
//判断是否登录
if(filter_has_var(INPUT_COOKIE, 'user')){
$user = unserialize(filter_input(INPUT_COOKIE, 'user'));
//print_r($user);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
<link rel="stylesheet" type="text/css" href="css/index.css">
</head>
<body>
<nav>
<a href="">首页</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>
2.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" type="text/css" href="css/style.css">
</head>
<body>
<h3>用户登录</h3>
<form action="handle.php?action=login" method="post">
<div>
<label for="email">邮箱:</label>
<input type="email" name="email" id="email" placeholder="zhangsan@email.com" required autofocus>
</div>
<div>
<label for="password">密码:</label>
<input type="password" name="password" id="password" placeholder="不少于6个字符">
</div>
<div>
<button>提交</button>
</div>
</form>
<a href="register.php">还没有帐号,点击注册</a>
</body>
</html>
3.register
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户注册</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h3>用户注册</h3>
<form action="handle.php?action=register" method="post" onsubmit="return compare()">
<div>
<label for="name">用户名:</label>
<input type="text" name="name" id="name" placeholder="zhangsan" required autofocus>
</div>
<div>
<label for="email">邮箱:</label>
<input type="email" name="email" id="email" placeholder="zhangsan@email.com" required>
</div>
<div>
<label for="password1">密码:</label>
<input type="password" name="password1" id="password1" placeholder="不少于6个字符">
</div>
<div>
<label for="password2">重复密码:</label>
<input type="password" name="password2" id="password2" placeholder="和上面输入一致">
</div>
<div>
<button>提交</button><span id="tips" style="color: red"></span>
</div>
</form>
<a href="login.php">已有帐号,点击登录</a>
<script>
// 验证二次密码是否相等?JS 课堂老师复制代码少button的id
function compare() {
if (document.forms[0].password1.value.trim() !== document.forms[0].password2.value.trim()) {
document.querySelector('#tips').innerText = '二次密码不相等';
return false;
}
}
</script>
</body>
</html>
4.handle
<?php
// 用户资料库, 实际项目中,应该用数据库
$users = [
[
'id' => 1,
'name' => 'admin',
'email' => 'admin@php.cn',
//sha1()加密密码
'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
],
[
'id' => 2,
'name' => 'dashu',
'email' => 'dashu@php.cn',
'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
],
];
// 1. 验证请求来源的合法性
// 设置合法请求地址的白名单
$allowUrls = ['index.php', 'login.php', 'register.php'];
// 获取当前的请求入口地址
//basename():获取当前请求脚本名称
$currentUrl = basename(filter_input(INPUT_SERVER, 'HTTP_REFERER'));
//in_array(),判断当前请求在不在白名单
if(!in_array($currentUrl, $allowUrls)){
echo '非法来源';
}else{
//echo '合法来源';
}
// 2.进行请求分发处理
//获取当前请求
//echo $_GET['action'];
//过滤处理, strtolower():字符串转为小写
$action = strtolower(filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING));
//switch判断当前请求
switch($action){
//登录
case 'login':
//判断是否是POST请求?
if(filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST'){
//获取当前请求的值:+清理特殊字符
$email = filter_var(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL), FILTER_SANITIZE_EMAIL);
$password = sha1(filter_input(INPUT_POST, 'password'));
//echo $email, $password;
//array_filter从数组中获取满足条件的值
$results = array_filter($users, function ($user)use($email, $password){
return $email === $user['email'] && $password === $user['password'];
});
//print_r($results);
if(count($results) === 1) {
//判断满足条件的指令数量=1?设置cookie
//array_pop()=$results[0]
setcookie('user', serialize(array_pop($results)));
//print_r(unserialize($_COOKIE['user']));
exit('<script>alert("验证通过");location.href="index.php"</script>');
}else{
exit('<script>alert("邮箱或密码错误,或没有帐号");location.href="register.php"</script>');
}
}else{
exit('非法请求。');
}
break;
//退出
case 'logout':
if(filter_input(INPUT_COOKIE,'user')){
setcookie('user',null,time()-3600);
exit('<script>alert("退出成功");location.href="index.php"</script>');
}
break;
//注册
case 'register':
$name = filter_var(filter_input(INPUT_POST, 'name'), FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_var(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL), FILTER_SANITIZE_EMAIL);
$password = sha1(filter_input(INPUT_POST, 'password1'));
$id = 3;
$data = compact('id', 'name', 'email', 'password');
//添加
//$users[] = $data;
//array_push($users,$data);
if(array_push($users, $data) === 1){
exit('<script>alert("注册成功");location.href="index.php"</script>');
}
print_r($users);
break;
//未定义操作
default:
exit('未定义操作');
}
首页:
登录:
注册:
SESSION
1、数据保存在服务器上
2、启动session:session_start()
3、创建session:$_SESSION['名称']=值
4、使用session:$_SESSION['名称']
5、删除单个session:unset($_SESSION['名称'])
6、删除所有的session:session_unset()
7、销毁session:session_destory()
1.handle
<?php
session_start();
if(count($results) === 1) {
//判断满足条件的指令数量=1?设置cookie
//array_pop()=$results[0]
//setcookie('user', serialize(array_pop($results)));
//session
$_SESSION['user'] = array_pop($results);
//print_r(unserialize($_COOKIE['user']));
case 'logout':
if(isset($_SESSION['user'])){
//setcookie('user',null,time()-3600);
//session
session_destroy();
exit('<script>alert("退出成功");location.href="index.php"</script>');
}
break;
2.index
<?php
//判断是否登录
/*if(filter_has_var(INPUT_COOKIE, 'user')){
$user = unserialize(filter_input(INPUT_COOKIE, 'user'));
//print_r($user);
}*/
//session
//开启
session_start();
if(isset($_SESSION['user'])){
$user = $_SESSION['user'];
}
?>
3.login
// 判断是否已登录?
/*if (filter_has_var(INPUT_COOKIE, 'user')) {
exit('<script>alert("请不要重复登录");location.href="index.php"</script>');
}*/
session_start();
if($_SESSION['user']) {
exit('<script>alert("请不要重复登录");location.href="index.php"</script>');
}
?>
登录验证流程图: