1、SESSION会话
1.1、连接数据库
1.1.1、配置参数
代码实例
<?php
namespace edu;
return [
'type'=>$type ?? 'mysql',
'host'=>$localhost ?? 'localhost',
'dbname'=>$dbname ?? 'goods',
'charset' =>$charset ?? 'utf-8',
'username'=>$username ?? 'root',
'password'=>$password ?? 'root'
];
?>
1.1.2、连接数据库
代码实例
<?php
namespace edu;
use Exception;
use PDO;
$conf = require 'conf.php';
$type = $conf['type'];
$host = $conf['host'];
$dbname = $conf['dbname'];
$username = $conf['username'];
$password = $conf['password'];
$dsn = sprintf('%s:host=%s;dbname=%s',$type,$host,$dbname);
try {
$db = new PDO($dsn, $username, $password);
} catch (Exception $e) {
echo '错误原因: ' . $e->getMessage();
}
?>
1.2、CSS样式
代码实例
.body{padding: 0px;margin: 0px;box-sizing: border-box;}
a{
text-decoration: none;
color:#ffffff;
padding: 5px 20px;
}
a:hover{
background-color: bisque;
color:#292828;
padding-left: 20px;
}
.login{
background-color: aquamarine;
width: 400px;
height:230px;
margin:10% auto ;
border-radius: 5px;
padding: 10px ;
display: flex;
flex-flow: column nowrap;
}
.login>div{
margin-top: 20px;
display: flex;
flex-flow: row nowrap;
align-self: center;
}
.login>div>button{
border: none;
background-color: forestgreen;
height: 25px;
width: 90px;
margin-left: 20px;
}
.login>div>button:hover{
background-color:#338c82;
color: ghostwhite;
}
.reg{
background-color: rgb(246, 247, 243);
width: 400px;
margin:auto ;
border-radius: 5px;
padding: 10px ;
display: flex;
flex-flow: column nowrap;
}
.reg>div{
margin-top: 20px;
display: flex;
flex-flow: row nowrap;
align-self: center;
}
.reg>div>input{
height:20px;
width: 200px;
font-size: 15px;
}
.reg>div>button{
border: none;
background-color: rgb(112, 134, 112);
height: 25px;
width: 90px;
margin-left: 20px;
}
.reg>div>button:hover{
background-color:#338c82;
color: ghostwhite;
}
.header{
width: 100%;
height:40px;
background-color: #252525;
color:#ffffff;
font-size: 20px;
display: flex;
flex-flow:row nowrap;
justify-content: space-around;
}
.header>div{
display: flex;
flex-flow:row nowrap;
align-self: center;
}
1.3、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/style.css">
<title>首页</title>
</head>
<body>
<div class="header">
<div>
<a href="#">首页</a>
<a href="#">商品展示</a>
<a href="#">购物车</a>
<a href="#">联系我们</a>
</div>
<div>
<?php if (isset($user)) : ?>
<span style="color:red;margin-top:5px;"><?php echo $user['name']?></span><a href="" id="logout"> 退出</a>
<?php else: ?>
<a href="login.php">登录</a>
<?php endif ?>
</div>
</div>
</body>
</html>
<script>
//为退出按钮创建事件监听器
document.querySelector('#logout').addEventListener('click', function(event) {
if (confirm('是否退出')) {
// 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
event.preventDefault();
// 跳转到退出事件处理器
window.location.assign('handle.php?action=logout');
}
});
</script>
1.4、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">
<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>
<form action="handle.php?action=login" method="post">
<div class="login">
<span>用户登录</span>
<span><hr></span>
<div>
<label>用户名:</label>
<input type="text" name="name" id="name" placeholder="请输入用户名" required autofocus>
</div>
<div>
<label>密 码:</label>
<input type="password" name="password" id="password" placeholder="请输入密码" required >
</div>
<div>
<button>登 录</button>
</div>
<div style="color:aqua;">
<a href="register.php">还没有帐号, 注册一个吧</a>
</div>
</div>
</form>
</body>
</html>
1.5、register
代码实例
<!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>
<form action="handle.php?action=register" method="post" onsubmit="return compare()">
<div class="reg">
<span>注册用户</span>
<span><hr></span>
<div>
<label>用 户 名:</label>
<input type="text" name="name" id="name" placeholder="请输入用户名" required autofocus>
</div>
<div>
<label>邮 箱:</label>
<input type="email" name="email" id="email" placeholder="请输入邮箱" required >
</div>
<div>
<label>密 码:</label>
<input type="password" name="pwd1" id="pwd1" placeholder="请输入密码" required >
</div>
<div>
<label>密码确认:</label>
<input type="password" name="pwd2" id="pwd2" placeholder="请再次输入密码" required >
</div>
<div>
<button>提 交</button>
</div>
</div>
</form>
</body>
</html>
<script>
// 验证二次密码是否相等?
function compare() {
if (document.forms[0].pwd1.value.trim() !== document.forms[0].pwd2.value.trim()) {
document.querySelector('#tips').innerText = '二次密码不相等';
return false;
}
}
</script>
1.6、hendle.php
代码实例
<?php
// 开启会话
session_start();
// 查询用户表中的数据
$pdo = new PDO('mysql:host=localhost;dbname=php11', 'root', 'root');
$stmt = $pdo->prepare('SELECT * FROM `users`');
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 处理用户登录与注册
$action = $_GET['action'];
switch ( strtolower($action)) {
// 登录
case 'login':
// 判断请求是否合t法
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 获取需要验证的数据
$name = $_POST['name'];
$password = md5($_POST['password']);
$results = array_filter($users, function($user) use ($name, $password) {
return $user['name'] === $name && $user['password'] === $password;
});
if (count($results) === 1) {
$_SESSION['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'])) {
session_destroy();
exit('<script>alert("退出成功");location.assign("index.php")</script>');
}
break;
// 注册
case 'register':
// 1. 获取到所有新用户数据
$name = $_POST['name'];
$email = $_POST['email'];
$password = sha1($_POST['pwd1']);
$add_time = time();
// 2. 将新用户插入到表中
$sql = "INSERT `users` SET `name`='{$name}', `email`='{$email}', `password`='{$password}', `add_time`={$add_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('未定义操作');
}
2、COOKIE会话
2.1、连接数据库
2.1.1、配置参数
代码实例
<?php
namespace edu;
return [
'type'=>$type ?? 'mysql',
'host'=>$localhost ?? 'localhost',
'dbname'=>$dbname ?? 'goods',
'charset' =>$charset ?? 'utf-8',
'username'=>$username ?? 'root',
'password'=>$password ?? 'root'
];
?>
2.1.2、连接数据库
代码实例
<?php
namespace edu;
use Exception;
use PDO;
$conf = require 'conf.php';
$type = $conf['type'];
$host = $conf['host'];
$dbname = $conf['dbname'];
$username = $conf['username'];
$password = $conf['password'];
$dsn = sprintf('%s:host=%s;dbname=%s',$type,$host,$dbname);
try {
$db = new PDO($dsn, $username, $password);
} catch (Exception $e) {
echo '错误原因: ' . $e->getMessage();
}
?>
2.2、CSS样式
代码实例
.body{padding: 0px;margin: 0px;box-sizing: border-box;}
a{
text-decoration: none;
color:#ffffff;
padding: 5px 20px;
}
a:hover{
background-color: bisque;
color:#292828;
padding-left: 20px;
}
.login{
background-color: aquamarine;
width: 400px;
height:230px;
margin:10% auto ;
border-radius: 5px;
padding: 10px ;
display: flex;
flex-flow: column nowrap;
}
.login>div{
margin-top: 20px;
display: flex;
flex-flow: row nowrap;
align-self: center;
}
.login>div>button{
border: none;
background-color: forestgreen;
height: 25px;
width: 90px;
margin-left: 20px;
}
.login>div>button:hover{
background-color:#338c82;
color: ghostwhite;
}
.reg{
background-color: rgb(246, 247, 243);
width: 400px;
margin:auto ;
border-radius: 5px;
padding: 10px ;
display: flex;
flex-flow: column nowrap;
}
.reg>div{
margin-top: 20px;
display: flex;
flex-flow: row nowrap;
align-self: center;
}
.reg>div>input{
height:20px;
width: 200px;
font-size: 15px;
}
.reg>div>button{
border: none;
background-color: rgb(112, 134, 112);
height: 25px;
width: 90px;
margin-left: 20px;
}
.reg>div>button:hover{
background-color:#338c82;
color: ghostwhite;
}
.header{
width: 100%;
height:40px;
background-color: #252525;
color:#ffffff;
font-size: 20px;
display: flex;
flex-flow:row nowrap;
justify-content: space-around;
}
.header>div{
display: flex;
flex-flow:row nowrap;
align-self: center;
}
2.3、index.php
代码实例
<?php
// 判断是否已经登录?
if (isset($_COOKIE['user'])) $user = unserialize($_COOKIE['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/style.css">
<title>首页</title>
</head>
<body>
<div class="header">
<div>
<a href="#">首页</a>
<a href="#">商品展示</a>
<a href="#">购物车</a>
<a href="#">联系我们</a>
</div>
<div>
<?php if (isset($user)) : ?>
<span style="color:red;margin-top:5px;"><?php echo $user['name']?></span><a href="" id="logout"> 退出</a>
<?php else: ?>
<a href="login.php">登录</a>
<?php endif ?>
</div>
</div>
</body>
</html>
<script>
//为退出按钮创建事件监听器
document.querySelector('#logout').addEventListener('click', function(event) {
if (confirm('是否退出')) {
// 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
event.preventDefault();
// 跳转到退出事件处理器
window.location.assign('handle.php?action=logout');
}
});
</script>
2.4、login.php
代码实例
<?php
// 判断是否已登录
if (isset($_COOKIE['user']))
exit('<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" type="text/css" href="css/style.css">
<title>登录页面</title>
</head>
<body>
<form action="handle.php?action=login" method="post">
<div class="login">
<span>用户登录</span>
<span><hr></span>
<div>
<label>用户名:</label>
<input type="text" name="name" id="name" placeholder="请输入用户名" required autofocus>
</div>
<div>
<label>密 码:</label>
<input type="password" name="password" id="password" placeholder="请输入密码" required >
</div>
<div>
<button>登 录</button>
</div>
<div style="color:aqua;">
<a href="register.php">还没有帐号, 注册一个吧</a>
</div>
</div>
</form>
</body>
</html>
2.5、register
代码实例
<!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>
<form action="handle.php?action=register" method="post" onsubmit="return compare()">
<div class="reg">
<span>注册用户</span>
<span><hr></span>
<div>
<label>用 户 名:</label>
<input type="text" name="name" id="name" placeholder="请输入用户名" required autofocus>
</div>
<div>
<label>邮 箱:</label>
<input type="email" name="email" id="email" placeholder="请输入邮箱" required >
</div>
<div>
<label>密 码:</label>
<input type="password" name="pwd1" id="pwd1" placeholder="请输入密码" required >
</div>
<div>
<label>密码确认:</label>
<input type="password" name="pwd2" id="pwd2" placeholder="请再次输入密码" required >
</div>
<div>
<button>提 交</button>
</div>
</div>
</form>
</body>
</html>
<script>
// 验证二次密码是否相等?
function compare() {
if (document.forms[0].pwd1.value.trim() !== document.forms[0].pwd2.value.trim()) {
document.querySelector('#tips').innerText = '二次密码不相等';
return false;
}
}
</script>
2.6、hendle.php
代码实例
<?php
// 查询用户表中的数据
$pdo = new PDO('mysql:host=localhost;dbname=php11', 'root', 'root');
$stmt = $pdo->prepare('SELECT * FROM `users`');
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 处理用户登录与注册
$action = $_GET['action'];
switch ( strtolower($action)) {
// 登录
case 'login':
// 判断请求是否合t法
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// 获取需要验证的数据
$name = $_POST['name'];
$password = md5($_POST['password']);
$results = array_filter($users, function($user) use ($name, $password) {
return $user['name'] === $name && $user['password'] === $password;
});
if (count($results) === 1) {
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($_COOKIE['user'])) {
setcookie('user', null , time()-3000);
exit('<script>alert("退出成功");location.assign("index.php")</script>');
}
break;
// 注册
case 'register':
// 1. 获取到所有新用户数据
$name = $_POST['name'];
$email = $_POST['email'];
$password = sha1($_POST['pwd1']);
$add_time = time();
// 2. 将新用户插入到表中
$sql = "INSERT `users` SET `name`='{$name}', `email`='{$email}', `password`='{$password}', `add_time`={$add_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('未定义操作');
}
3、学习总结
本节课我们学习了有关PHP的会话知识,通过本节课的学习使我学会了如何使用SESSION和COOKIE,通过SESSION或者COOKIE来判断用户是否已经登录,有助于以后的实战应用。