SESSION实现用户登录、记录、退出登录
连接数据库 connect.php
<?php
$db = [
'type' => 'mysql',
'host' => 'localhost',
'dbname' => 'php_2019',
'username' => 'root',
'password' => '********'
];
$dsn = "{$db['type']}:host={$db['host']};dbname={$db['dbname']}";
$username = $db['username'];
$password = $db['password'];
try{
$pdo = new PDO($dsn,$username,$password);
}catch(PDOException $e){
die('连接失败'.$e->getMessage());
}
user表已创建
1.index.php
<?php
session_start();
//主页
if(isset($_SESSION['name']))
{
echo '用户:'.$_SESSION['name'].'已登录<br>';
echo '<a href="dispatch.php?action=logout">退出登录</a>';
}else{
echo '<a href="dispatch.php?action=login">请登录</a>';
}
2.dispatch.php
<?php
//开启会话
session_start();
//请求连接数据库
require __DIR__ . '/connect.php';
//获取请求参数
$action = isset($_GET['action']) ? $_GET['action'] : 'login';
$action = htmlentities(strtolower(trim($action)));
//请求路由
switch ($action){
case 'login':
include __DIR__.'/login.php';
break;
case 'check':
include __DIR__.'/check.php';
break;
case 'logout':
include __DIR__.'/logout.php';
break;
default:
header('Location:index.php');
echo '<script>location.assign("index.php");</script>';
}
3.login.php
<?php
if(isset($_SESSION['name'])){
echo '<script>alert("您已登录,请不要重复登录");location.assign("index.php");</script>';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<h3>用户登录</h3>
<form action="dispatch.php?action=check" method="post">
<p>
<label for="name">用户名:</label>
<input type="text" name="name" id="name">
</p>
<p>
<label for="password">密码:</label>
<input type="password" name="password" id="password">
</p>
<p><button>登录</button></p>
</form>
</body>
</html>
4.check.php
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
if(!empty($_POST['name']) && !empty($_POST['password'])){
$name = $_POST['name'];
$password = $_POST['password'];
$sql = 'SELECT * FROM `user` WHERE `username` = :username AND `password` = :password LIMIT 1';
$stmt = $pdo->prepare($sql);
$stmt->execute(['username'=>$name,'password'=>$password]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}else{
echo '<script>alert("用户名或密码未填写");location.assign("login.php");</script>';
}
if($user === false){
echo '验证失败';
die;
}
//验证成功 写入session
$_SESSION['name'] = $user['username'];
echo '<script>alert("登录成功");location.assign("index.php");</script>';
exit;
}else{
die('请求类型错误');
}
5.logout.php
<?php
if(isset($_SESSION['name'])){
//清除session
session_destroy();
echo '<script>alert("退出成功");location.assign("index.php");</script>';
}else{
echo '<script>alert("请先登录");location.assign("index.php")</script>';
}
index.php
login.php
index.php
logout.php
手抄:
总结:经过这次课程,搞明白了session和cookie的作用和它们的区别。以前对这两个概念只是知道也看了很多遍相关的知识,但是不会用。cookie和session用于在同一个网站项目中不同的页面之间传递用户数据,让用户实现只输入一次数据就可以把数据保存下来在每一个页面中都可以使用。课上老师介绍的很清楚。session数据存在服务端,session的id以cookie的形式保存在客户端以便于服务器区分用户对应的是哪个session文件。