博客列表 >SESSION与COOKIE案例

SESSION与COOKIE案例

phpcn_u202398
phpcn_u202398原创
2020年05月11日 18:35:17598浏览

1、SESSION会话

1.1、连接数据库

1.1.1、配置参数
代码实例
  1. <?php
  2. namespace edu;
  3. return [
  4. 'type'=>$type ?? 'mysql',
  5. 'host'=>$localhost ?? 'localhost',
  6. 'dbname'=>$dbname ?? 'goods',
  7. 'charset' =>$charset ?? 'utf-8',
  8. 'username'=>$username ?? 'root',
  9. 'password'=>$password ?? 'root'
  10. ];
  11. ?>

1.1.2、连接数据库
代码实例
  1. <?php
  2. namespace edu;
  3. use Exception;
  4. use PDO;
  5. $conf = require 'conf.php';
  6. $type = $conf['type'];
  7. $host = $conf['host'];
  8. $dbname = $conf['dbname'];
  9. $username = $conf['username'];
  10. $password = $conf['password'];
  11. $dsn = sprintf('%s:host=%s;dbname=%s',$type,$host,$dbname);
  12. try {
  13. $db = new PDO($dsn, $username, $password);
  14. } catch (Exception $e) {
  15. echo '错误原因: ' . $e->getMessage();
  16. }
  17. ?>

1.2、CSS样式

代码实例
  1. .body{padding: 0px;margin: 0px;box-sizing: border-box;}
  2. a{
  3. text-decoration: none;
  4. color:#ffffff;
  5. padding: 5px 20px;
  6. }
  7. a:hover{
  8. background-color: bisque;
  9. color:#292828;
  10. padding-left: 20px;
  11. }
  12. .login{
  13. background-color: aquamarine;
  14. width: 400px;
  15. height:230px;
  16. margin:10% auto ;
  17. border-radius: 5px;
  18. padding: 10px ;
  19. display: flex;
  20. flex-flow: column nowrap;
  21. }
  22. .login>div{
  23. margin-top: 20px;
  24. display: flex;
  25. flex-flow: row nowrap;
  26. align-self: center;
  27. }
  28. .login>div>button{
  29. border: none;
  30. background-color: forestgreen;
  31. height: 25px;
  32. width: 90px;
  33. margin-left: 20px;
  34. }
  35. .login>div>button:hover{
  36. background-color:#338c82;
  37. color: ghostwhite;
  38. }
  39. .reg{
  40. background-color: rgb(246, 247, 243);
  41. width: 400px;
  42. margin:auto ;
  43. border-radius: 5px;
  44. padding: 10px ;
  45. display: flex;
  46. flex-flow: column nowrap;
  47. }
  48. .reg>div{
  49. margin-top: 20px;
  50. display: flex;
  51. flex-flow: row nowrap;
  52. align-self: center;
  53. }
  54. .reg>div>input{
  55. height:20px;
  56. width: 200px;
  57. font-size: 15px;
  58. }
  59. .reg>div>button{
  60. border: none;
  61. background-color: rgb(112, 134, 112);
  62. height: 25px;
  63. width: 90px;
  64. margin-left: 20px;
  65. }
  66. .reg>div>button:hover{
  67. background-color:#338c82;
  68. color: ghostwhite;
  69. }
  70. .header{
  71. width: 100%;
  72. height:40px;
  73. background-color: #252525;
  74. color:#ffffff;
  75. font-size: 20px;
  76. display: flex;
  77. flex-flow:row nowrap;
  78. justify-content: space-around;
  79. }
  80. .header>div{
  81. display: flex;
  82. flex-flow:row nowrap;
  83. align-self: center;
  84. }

1.3、index.php

代码实例
  1. <?php
  2. // 开启会话
  3. session_start();
  4. // 判断是否已经登录?
  5. if (isset($_SESSION['user'])) $user = unserialize($_SESSION['user']);
  6. ?>
  7. <!DOCTYPE html>
  8. <html lang="en">
  9. <head>
  10. <meta charset="UTF-8">
  11. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  12. <link rel="stylesheet" type="text/css" href="css/style.css">
  13. <title>首页</title>
  14. </head>
  15. <body>
  16. <div class="header">
  17. <div>
  18. <a href="#">首页</a>
  19. <a href="#">商品展示</a>
  20. <a href="#">购物车</a>
  21. <a href="#">联系我们</a>
  22. </div>
  23. <div>
  24. <?php if (isset($user)) : ?>
  25. <span style="color:red;margin-top:5px;"><?php echo $user['name']?></span><a href="" id="logout">&nbsp;&nbsp;退出</a>
  26. <?php else: ?>
  27. <a href="login.php">登录</a>
  28. <?php endif ?>
  29. </div>
  30. </div>
  31. </body>
  32. </html>
  33. <script>
  34. //为退出按钮创建事件监听器
  35. document.querySelector('#logout').addEventListener('click', function(event) {
  36. if (confirm('是否退出')) {
  37. // 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
  38. event.preventDefault();
  39. // 跳转到退出事件处理器
  40. window.location.assign('handle.php?action=logout');
  41. }
  42. });
  43. </script>

1.4、login.php

代码实例
  1. <?php
  2. // 开启会话
  3. session_start();
  4. // 判断是否已登录
  5. if (isset($_SESSION['user']))
  6. exit('<script>alert("请不要重复登录");location.href="index.php";</script>');
  7. ?>
  8. <!DOCTYPE html>
  9. <html lang="en">
  10. <head>
  11. <meta charset="UTF-8">
  12. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  13. <link rel="stylesheet" type="text/css" href="css/style.css">
  14. <title>登录页面</title>
  15. </head>
  16. <body>
  17. <form action="handle.php?action=login" method="post">
  18. <div class="login">
  19. <span>用户登录</span>
  20. <span><hr></span>
  21. <div>
  22. <label>用户名:</label>
  23. <input type="text" name="name" id="name" placeholder="请输入用户名" required autofocus>
  24. </div>
  25. <div>
  26. <label>密&nbsp;&nbsp;&nbsp;&nbsp;码:</label>
  27. <input type="password" name="password" id="password" placeholder="请输入密码" required >
  28. </div>
  29. <div>
  30. <button>登&nbsp;&nbsp;&nbsp;&nbsp;录</button>
  31. </div>
  32. <div style="color:aqua;">
  33. <a href="register.php">还没有帐号, 注册一个吧</a>
  34. </div>
  35. </div>
  36. </form>
  37. </body>
  38. </html>

1.5、register

代码实例
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <link rel="stylesheet" type="text/css" href="css/style.css">
  7. <title>注册页面</title>
  8. </head>
  9. <body>
  10. <form action="handle.php?action=register" method="post" onsubmit="return compare()">
  11. <div class="reg">
  12. <span>注册用户</span>
  13. <span><hr></span>
  14. <div>
  15. <label>用&nbsp;&nbsp;户&nbsp;&nbsp;名:</label>
  16. <input type="text" name="name" id="name" placeholder="请输入用户名" required autofocus>
  17. </div>
  18. <div>
  19. <label>邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱:</label>
  20. <input type="email" name="email" id="email" placeholder="请输入邮箱" required >
  21. </div>
  22. <div>
  23. <label>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码:</label>
  24. <input type="password" name="pwd1" id="pwd1" placeholder="请输入密码" required >
  25. </div>
  26. <div>
  27. <label>密码确认:</label>
  28. <input type="password" name="pwd2" id="pwd2" placeholder="请再次输入密码" required >
  29. </div>
  30. <div>
  31. <button>提&nbsp;&nbsp;&nbsp;&nbsp;交</button>
  32. </div>
  33. </div>
  34. </form>
  35. </body>
  36. </html>
  37. <script>
  38. // 验证二次密码是否相等?
  39. function compare() {
  40. if (document.forms[0].pwd1.value.trim() !== document.forms[0].pwd2.value.trim()) {
  41. document.querySelector('#tips').innerText = '二次密码不相等';
  42. return false;
  43. }
  44. }
  45. </script>

1.6、hendle.php

代码实例
  1. <?php
  2. // 开启会话
  3. session_start();
  4. // 查询用户表中的数据
  5. $pdo = new PDO('mysql:host=localhost;dbname=php11', 'root', 'root');
  6. $stmt = $pdo->prepare('SELECT * FROM `users`');
  7. $stmt->execute();
  8. $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
  9. // 处理用户登录与注册
  10. $action = $_GET['action'];
  11. switch ( strtolower($action)) {
  12. // 登录
  13. case 'login':
  14. // 判断请求是否合t法
  15. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  16. // 获取需要验证的数据
  17. $name = $_POST['name'];
  18. $password = md5($_POST['password']);
  19. $results = array_filter($users, function($user) use ($name, $password) {
  20. return $user['name'] === $name && $user['password'] === $password;
  21. });
  22. if (count($results) === 1) {
  23. $_SESSION['user'] = serialize(array_pop($results));
  24. exit('<script>alert("验证通过");location.href="index.php"</script>');
  25. } else {
  26. exit('<script>alert("用户名或密码错误");location.href="login.php";</script>');
  27. }
  28. } else {
  29. die('请求类型错误');
  30. }
  31. break;
  32. // 退出
  33. case 'logout':
  34. if (isset($_SESSION['user'])) {
  35. session_destroy();
  36. exit('<script>alert("退出成功");location.assign("index.php")</script>');
  37. }
  38. break;
  39. // 注册
  40. case 'register':
  41. // 1. 获取到所有新用户数据
  42. $name = $_POST['name'];
  43. $email = $_POST['email'];
  44. $password = sha1($_POST['pwd1']);
  45. $add_time = time();
  46. // 2. 将新用户插入到表中
  47. $sql = "INSERT `users` SET `name`='{$name}', `email`='{$email}', `password`='{$password}', `add_time`={$add_time}";
  48. $stmt = $pdo->prepare($sql);
  49. $stmt->execute();
  50. if ($stmt->rowCount() === 1) exit('<script>alert("注册成功");location.assign("login.php")</script>');
  51. else exit('<script>alert("注册失败");location.assign("login.php")</script>');
  52. break;
  53. // 未定义
  54. default:
  55. exit('未定义操作');
  56. }

2.1、连接数据库

2.1.1、配置参数
代码实例
  1. <?php
  2. namespace edu;
  3. return [
  4. 'type'=>$type ?? 'mysql',
  5. 'host'=>$localhost ?? 'localhost',
  6. 'dbname'=>$dbname ?? 'goods',
  7. 'charset' =>$charset ?? 'utf-8',
  8. 'username'=>$username ?? 'root',
  9. 'password'=>$password ?? 'root'
  10. ];
  11. ?>

2.1.2、连接数据库
代码实例
  1. <?php
  2. namespace edu;
  3. use Exception;
  4. use PDO;
  5. $conf = require 'conf.php';
  6. $type = $conf['type'];
  7. $host = $conf['host'];
  8. $dbname = $conf['dbname'];
  9. $username = $conf['username'];
  10. $password = $conf['password'];
  11. $dsn = sprintf('%s:host=%s;dbname=%s',$type,$host,$dbname);
  12. try {
  13. $db = new PDO($dsn, $username, $password);
  14. } catch (Exception $e) {
  15. echo '错误原因: ' . $e->getMessage();
  16. }
  17. ?>

2.2、CSS样式

代码实例
  1. .body{padding: 0px;margin: 0px;box-sizing: border-box;}
  2. a{
  3. text-decoration: none;
  4. color:#ffffff;
  5. padding: 5px 20px;
  6. }
  7. a:hover{
  8. background-color: bisque;
  9. color:#292828;
  10. padding-left: 20px;
  11. }
  12. .login{
  13. background-color: aquamarine;
  14. width: 400px;
  15. height:230px;
  16. margin:10% auto ;
  17. border-radius: 5px;
  18. padding: 10px ;
  19. display: flex;
  20. flex-flow: column nowrap;
  21. }
  22. .login>div{
  23. margin-top: 20px;
  24. display: flex;
  25. flex-flow: row nowrap;
  26. align-self: center;
  27. }
  28. .login>div>button{
  29. border: none;
  30. background-color: forestgreen;
  31. height: 25px;
  32. width: 90px;
  33. margin-left: 20px;
  34. }
  35. .login>div>button:hover{
  36. background-color:#338c82;
  37. color: ghostwhite;
  38. }
  39. .reg{
  40. background-color: rgb(246, 247, 243);
  41. width: 400px;
  42. margin:auto ;
  43. border-radius: 5px;
  44. padding: 10px ;
  45. display: flex;
  46. flex-flow: column nowrap;
  47. }
  48. .reg>div{
  49. margin-top: 20px;
  50. display: flex;
  51. flex-flow: row nowrap;
  52. align-self: center;
  53. }
  54. .reg>div>input{
  55. height:20px;
  56. width: 200px;
  57. font-size: 15px;
  58. }
  59. .reg>div>button{
  60. border: none;
  61. background-color: rgb(112, 134, 112);
  62. height: 25px;
  63. width: 90px;
  64. margin-left: 20px;
  65. }
  66. .reg>div>button:hover{
  67. background-color:#338c82;
  68. color: ghostwhite;
  69. }
  70. .header{
  71. width: 100%;
  72. height:40px;
  73. background-color: #252525;
  74. color:#ffffff;
  75. font-size: 20px;
  76. display: flex;
  77. flex-flow:row nowrap;
  78. justify-content: space-around;
  79. }
  80. .header>div{
  81. display: flex;
  82. flex-flow:row nowrap;
  83. align-self: center;
  84. }

2.3、index.php

代码实例
  1. <?php
  2. // 判断是否已经登录?
  3. if (isset($_COOKIE['user'])) $user = unserialize($_COOKIE['user']);
  4. ?>
  5. <!DOCTYPE html>
  6. <html lang="en">
  7. <head>
  8. <meta charset="UTF-8">
  9. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  10. <link rel="stylesheet" type="text/css" href="css/style.css">
  11. <title>首页</title>
  12. </head>
  13. <body>
  14. <div class="header">
  15. <div>
  16. <a href="#">首页</a>
  17. <a href="#">商品展示</a>
  18. <a href="#">购物车</a>
  19. <a href="#">联系我们</a>
  20. </div>
  21. <div>
  22. <?php if (isset($user)) : ?>
  23. <span style="color:red;margin-top:5px;"><?php echo $user['name']?></span><a href="" id="logout">&nbsp;&nbsp;退出</a>
  24. <?php else: ?>
  25. <a href="login.php">登录</a>
  26. <?php endif ?>
  27. </div>
  28. </div>
  29. </body>
  30. </html>
  31. <script>
  32. //为退出按钮创建事件监听器
  33. document.querySelector('#logout').addEventListener('click', function(event) {
  34. if (confirm('是否退出')) {
  35. // 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
  36. event.preventDefault();
  37. // 跳转到退出事件处理器
  38. window.location.assign('handle.php?action=logout');
  39. }
  40. });
  41. </script>

2.4、login.php

代码实例
  1. <?php
  2. // 判断是否已登录
  3. if (isset($_COOKIE['user']))
  4. exit('<script>alert("请不要重复登录");location.href="index.php";</script>');
  5. ?>
  6. <!DOCTYPE html>
  7. <html lang="en">
  8. <head>
  9. <meta charset="UTF-8">
  10. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  11. <link rel="stylesheet" type="text/css" href="css/style.css">
  12. <title>登录页面</title>
  13. </head>
  14. <body>
  15. <form action="handle.php?action=login" method="post">
  16. <div class="login">
  17. <span>用户登录</span>
  18. <span><hr></span>
  19. <div>
  20. <label>用户名:</label>
  21. <input type="text" name="name" id="name" placeholder="请输入用户名" required autofocus>
  22. </div>
  23. <div>
  24. <label>密&nbsp;&nbsp;&nbsp;&nbsp;码:</label>
  25. <input type="password" name="password" id="password" placeholder="请输入密码" required >
  26. </div>
  27. <div>
  28. <button>登&nbsp;&nbsp;&nbsp;&nbsp;录</button>
  29. </div>
  30. <div style="color:aqua;">
  31. <a href="register.php">还没有帐号, 注册一个吧</a>
  32. </div>
  33. </div>
  34. </form>
  35. </body>
  36. </html>

2.5、register

代码实例
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <link rel="stylesheet" type="text/css" href="css/style.css">
  7. <title>注册页面</title>
  8. </head>
  9. <body>
  10. <form action="handle.php?action=register" method="post" onsubmit="return compare()">
  11. <div class="reg">
  12. <span>注册用户</span>
  13. <span><hr></span>
  14. <div>
  15. <label>用&nbsp;&nbsp;户&nbsp;&nbsp;名:</label>
  16. <input type="text" name="name" id="name" placeholder="请输入用户名" required autofocus>
  17. </div>
  18. <div>
  19. <label>邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱:</label>
  20. <input type="email" name="email" id="email" placeholder="请输入邮箱" required >
  21. </div>
  22. <div>
  23. <label>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码:</label>
  24. <input type="password" name="pwd1" id="pwd1" placeholder="请输入密码" required >
  25. </div>
  26. <div>
  27. <label>密码确认:</label>
  28. <input type="password" name="pwd2" id="pwd2" placeholder="请再次输入密码" required >
  29. </div>
  30. <div>
  31. <button>提&nbsp;&nbsp;&nbsp;&nbsp;交</button>
  32. </div>
  33. </div>
  34. </form>
  35. </body>
  36. </html>
  37. <script>
  38. // 验证二次密码是否相等?
  39. function compare() {
  40. if (document.forms[0].pwd1.value.trim() !== document.forms[0].pwd2.value.trim()) {
  41. document.querySelector('#tips').innerText = '二次密码不相等';
  42. return false;
  43. }
  44. }
  45. </script>

2.6、hendle.php

代码实例
  1. <?php
  2. // 查询用户表中的数据
  3. $pdo = new PDO('mysql:host=localhost;dbname=php11', 'root', 'root');
  4. $stmt = $pdo->prepare('SELECT * FROM `users`');
  5. $stmt->execute();
  6. $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
  7. // 处理用户登录与注册
  8. $action = $_GET['action'];
  9. switch ( strtolower($action)) {
  10. // 登录
  11. case 'login':
  12. // 判断请求是否合t法
  13. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  14. // 获取需要验证的数据
  15. $name = $_POST['name'];
  16. $password = md5($_POST['password']);
  17. $results = array_filter($users, function($user) use ($name, $password) {
  18. return $user['name'] === $name && $user['password'] === $password;
  19. });
  20. if (count($results) === 1) {
  21. setcookie('user', serialize(array_pop($results)));
  22. exit('<script>alert("验证通过");location.href="index.php"</script>');
  23. } else {
  24. exit('<script>alert("用户名或密码错误");location.href="login.php";</script>');
  25. }
  26. } else {
  27. die('请求类型错误');
  28. }
  29. break;
  30. // 退出
  31. case 'logout':
  32. if (isset($_COOKIE['user'])) {
  33. setcookie('user', null , time()-3000);
  34. exit('<script>alert("退出成功");location.assign("index.php")</script>');
  35. }
  36. break;
  37. // 注册
  38. case 'register':
  39. // 1. 获取到所有新用户数据
  40. $name = $_POST['name'];
  41. $email = $_POST['email'];
  42. $password = sha1($_POST['pwd1']);
  43. $add_time = time();
  44. // 2. 将新用户插入到表中
  45. $sql = "INSERT `users` SET `name`='{$name}', `email`='{$email}', `password`='{$password}', `add_time`={$add_time}";
  46. $stmt = $pdo->prepare($sql);
  47. $stmt->execute();
  48. if ($stmt->rowCount() === 1) exit('<script>alert("注册成功");location.assign("login.php")</script>');
  49. else exit('<script>alert("注册失败");location.assign("login.php")</script>');
  50. break;
  51. // 未定义
  52. default:
  53. exit('未定义操作');
  54. }

3、学习总结

本节课我们学习了有关PHP的会话知识,通过本节课的学习使我学会了如何使用SESSION和COOKIE,通过SESSION或者COOKIE来判断用户是否已经登录,有助于以后的实战应用。

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议