COOKIE
1、数据保存在客户端浏览器上,如果浏览器关闭cookie,则无法使用
2、创建cookie:setcookie(名称,值,[过期时间])
3、使用cookie:$_COOKIE[‘名称’]
4、删除cookie:为cookie设置一个已经过期的时间,如:setcookie(名称,值,time()-1)
SESSION
1、数据保存在服务器上
2、启动session:session_start()
3、创建session:$_SESSION[‘名称’]=值
4、使用session:$_SESSION[‘名称’]
5、删除单个session:unset($_SESSION[‘名称’])
6、删除所有的session:session_unset()
7、销毁session:session_destory()
handle.php
<?php
//echo phpinfo();
// 开启会话
session_start();
// 查询用户表中的数据
$pdo = new PDO('mysql:host=localhost;dbname=phpedu','root','root');
$sql = 'SELECT * FROM `user`';
$stmt = $pdo->prepare($sql);
$stmt->execute();
$users = $stmt->fetchALL(PDO::FETCH_ASSOC);
// 处理用户登录与注册
$action = $_GET['action'];
switch(strtolower($action))
{
case 'login':
// 判断请求是否合t法
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 获取需要验证的数据
$email = $_POST['email'];
$password = sha1($_POST['password']);
//array_filter(): 用回调过滤数组中的单元,返回计算结果为true的元素组成的数组
//判断验证的邮箱和密码是否在数据库中存在
$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));
//将身份信息序列化存到cookie中
//setcookie('user', serialize(array_pop($results)));
exit('<script>alert("验证通过");location.href="index.php"</script>');
} else {
exit('<script>alert("邮箱或密码错误,或者还没有帐号");location.href="login.php";</script>');
}
} else {
die('请求类型错误');
}
break;
case 'logout' :
if(isset($_SESSION['user'])){
unset($_SESSION);
session_destroy();
setcookie('user','',time()-3600);
//将身份信息从cookie中删除
//setcookie('user', null , time()-3600);
}
break;
case 'register' :
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$data['name'] = $_POST['name'];
$data['email'] = $_POST['email'];
$data['password'] = $_POST['p1'];
$data['add_time'] = time();
//注册前判断数据库只是否存在重复的邮箱
$results = array_filter($users,function ($user) use($email){
if($user['email'] == $email){
return false;
}else{
return true;
}
});
// $keys = array_keys($data);
// $values = array_values($data);
// array_walk($keys,function (&$item,$key){
// $item = "`$item`";
// });
// array_walk($values,function (&$item,$key){
// $item = "'$item'";
// });
//将获取到的数据封装成sql语句
$keys = [];
$values = [];
array_walk($data,function ($item,$key){
$keys[] = "`$key`";
$values[] = "'$item'";
});
$keys = implode(',',$keys);
$values = implode(',',$values);
if($results){
$sql = "INSERT `user` ($keys) VALUES ($values)";
$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;
}
}else{
die('请求类型错误');
}
}
index.php
<?php
// 开启会话
session_start();
// 判断是否已经登录?
if (isset($_SESSION['user'])) $user = unserialize($_SESSION['user']);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="./css/index.css">
<title>首页</title>
</head>
<body>
<nav>
<a href="index.php">我的论坛</a>
<?php if (isset($user)) : ?>
<a href="" id="logout"><span style="color:red"><?php echo $user['name']?></span> 退出</a>
<?php else: ?>
<a href="login.php">登录</a>
<?php endif ?>
</nav>
</body>
<script>
// 为退出按钮创建事件监听器
document.querySelector('#logout').addEventListener('click', function(event) {
if (confirm('是否退出')) {
// 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
event.preventDefault();
// 跳转到退出事件处理器
window.location.assign('handle.php?action=logout');
}
});
</script>
</html>
login.php
<?php
// 开启会话
session_start();
// 判断是否已登录
if (isset($_SESSION['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?1.0">
</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>
register.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="./css/style.css">
<title>注册用户</title>
</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>