Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:是的, 整个业务逻辑才是重点, 到于将用户数据存储在哪, 完全由程序员决定 , 而且就几行代码
1、数据保存在客户端浏览器上,如果浏览器关闭cookie,则无法使用
2、创建cookie:setcookie(名称,值,[过期时间])
3、使用cookie:$_COOKIE['名称']
4、删除cookie:为cookie设置一个已经过期的时间,如:setcookie(名称,值,time()-1)
首页:
<?php
// 判断是否已经登录?
if (isset($_COOKIE['user'])) $user = unserialize($_COOKIE['user']);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
<style>
nav {
height: 60px;
background-color: black;
padding: 0 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
nav a {
color: white;
text-decoration: none;
}
div {
display: flex;
align-items: center;
}
nav img {
width: 40px;
border-radius: 50%;
margin-right: 10px;
}
</style>
</head>
<body>
<nav>
<a href="index.php">我的博客</a>
<div>
<?php if (isset($user)) : ?>
<a href=""><img src="user.jpg" alt=""></a>
<a href="" id="logout"><span style="color:red"><?php echo $user['name']?></span> 退出</a>
<?php else: ?>
<a href="login.php">登录</a>
<?php endif ?>
</div>
</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>
登录:
<?php
// 判断是否已登录
if (isset($_COOKIE['user']))
exit('<script>alert("请不要重复登录");location.href="index.php";</script>');
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
<style>
body {
display: flex;
flex-direction: column;
text-align: center;
color: #555;
font-weight: 300;
}
body h3 {
font-weight: 300;
font-size: 20px;
margin-bottom: 10px;
}
body form {
width: 260px;
padding: 20px;
box-sizing: border-box;
background-color: lightcyan;
margin: auto;
border-radius: 5px;
box-shadow: 0 0 5px #aaa;
}
body form > div {
height: 36px;
display: flex;
justify-content: space-between;
align-items: center;
}
body form div:last-of-type {
display: flex;
justify-content: center;
}
body form input {
border: none;
outline: none;
padding-left: 5px;
height: 20px;
}
body form input:hover {
box-shadow: 0 0 5px #aaa;
}
body form button {
flex:auto;
height: 30px;
background-color: green;
color: white;
border: none;
outline: none;
}
body form button:hover {
background-color: lightcoral;
cursor: pointer;
box-shadow: 0 0 5px #aaa;
}
body a {
color: #888;
text-decoration: none;
margin-top: 15px;
}
body a:hover {
color: lightcoral;
}
</style>
</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="demo@email.com" required autofocus>
</div>
<div>
<label for="password">密码:</label>
<input type="password" name="password" id="password" placeholder="不少于6位" required>
</div>
<div>
<button>提交</button>
</div>
</form>
<a href="register.php">还没有帐号, 注册一个吧</a>
</body>
</html>
注册:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
<style>
body {
display: flex;
flex-direction: column;
text-align: center;
color: #555;
font-weight: 300;
}
body h3 {
font-weight: 300;
font-size: 20px;
margin-bottom: 10px;
}
body form {
width: 260px;
padding: 20px;
box-sizing: border-box;
background-color: lightcyan;
margin: auto;
border-radius: 5px;
box-shadow: 0 0 5px #aaa;
}
body form > div {
height: 36px;
display: flex;
justify-content: space-between;
align-items: center;
}
body form div:last-of-type {
display: flex;
justify-content: center;
}
body form input {
border: none;
outline: none;
padding-left: 5px;
height: 20px;
}
body form input:hover {
box-shadow: 0 0 5px #aaa;
}
body form button {
flex:auto;
height: 30px;
background-color: green;
color: white;
border: none;
outline: none;
}
body form button:hover {
background-color: lightcoral;
cursor: pointer;
box-shadow: 0 0 5px #aaa;
}
body a {
color: #888;
text-decoration: none;
margin-top: 15px;
}
body a:hover {
color: lightcoral;
}
</style>
</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="不少于3个字符" required autofocus>
</div>
<div>
<label for="email">邮箱:</label>
<input type="email" name="email" id="email" placeholder="demo@email.com" required>
</div>
<div>
<label for="p1">密码:</label>
<input type="password" name="p1" id="p1" placeholder="不少于6位" required>
</div>
<div>
<label for="p2">重复:</label>
<input type="password" name="p2" id="p2" placeholder="必须与上面一致" required>
</div>
<div>
<button>提交</button><span id="tips" style="color: red"></span>
</div>
</form>
<a href="login.php">我有帐号,直接登录</a>
<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>
控制器:
<?php
// 数据库查询用户资料
$pdo = new PDO('mysql:host=localhost;dbname=phpedu', 'root', 'root');
$stmt = $pdo->prepare('SELECT * FROM `users`');
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
// print_r($users);die;
// 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 .'<hr>';
//array_filter从数组中获取满足条件的值
$results = array_filter($users, function ($user)use($email, $password){
return $email === $user['email'] && $password === $user['password'];
});
// print_r($results);die;
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 (isset($_COOKIE['user'])) {
setcookie('user', null , time()-3600);
exit('<script>alert("退出成功");location.assign("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, 'p1'));
$register_time = time();
// echo $name .$email .$password .$register_time;die;
// 2. 将新用户插入到表中
$sql = "INSERT `users` SET `name`='{$name}', `password`='{$password}', `email`='{$email}', `register_time`={$register_time}";
$stmt = $pdo->prepare($sql);
$stmt->execute();
if ($stmt->rowCount() === 1) exit('<script>alert("注册成功");location.assign("login.php")</script>');
else exit('<script>alert("注册失败");location.assign("login.php")</script>');
break;
//未定义操作
default:
exit('未定义操作');
}
效果图:
首页:
登录:
注册:
1、数据保存在服务器上
2、启动session:session_start()
3、创建session:$_SESSION['名称']=值
4、使用session:$_SESSION['名称']
5、删除单个session:unset($_SESSION['名称'])
6、删除所有的session:session_unset()
7、销毁session:session_destory()
首页:
<?php
// 开启会话
session_start();
// 判断是否已经登录?
if (isset($_SESSION['user'])) $user = unserialize($_SESSION['user']);
?>
登录:
<?php
// 开启会话
session_start();
// 判断是否已登录
if (isset($_SESSION['user']))
exit('<script>alert("请不要重复登录");location.href="index.php";</script>');
?>
控制器:
<?php
// 开启会话
session_start();
// ......
if(count($results) === 1) {
//判断满足条件的指令数量=1?设置cookie
//array_pop()=$results[0]
$_SESSION['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>');
}
case 'logout':
if (isset($_SESSION['user'])) {
session_destroy();
exit('<script>alert("退出成功");location.assign("index.php")</script>');
}
break;
cookie、session
都不是很难,我觉得难的是设置cookie和session
之前的数据处理与及控制器逻辑。