Blogger Information
Blog 47
fans 1
comment 0
visits 53080
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP-会话控制
晴天
Original
682 people have browsed it

演示地址点这里

1. 会话控制

  • HTTP 是基于无连接的网络协议, 每一次访问, 对于服务器来说, 都是全新的
  • 如果记住访问者,以及记录连接状态, 可以提升用户体验,完成许多个性化的功能
  • 例如, 用户登录, 购物车等
  • 其实让服务器记住用户的方式很简单, 就和生活中, 我们办会员卡是一样的
  • 会员卡的存储位置有二个地方, 要么放在你身上, 要么保存到商家电脑中
  • 所以, 网络中的用户资料也会保存在二个地方: 浏览器(客户端)和服务器中
  • 保存到浏览器中的叫: cookie
  • 保存到服务器中的叫: session

  • 保存在客户端
  • 变量: $_COOKIE
  • 变量过滤器: filter_input(INPUT_COOKIE, key)
  • 设置使用专用函数: setcookie(名称, 值, 过期时间)
  • 生效需要分二步完成: 先下达指令到浏览器, 再由浏览器完成 cookie 写入

3. SESSION

  • 保存在服务器端
  • 变量: $_SESSION
  • 变量过滤器: filter_input(INPUT_SESSION, key)
  • 设置使用专用函数: setcookie(名称, 值, 过期时间)
  • 生效需要分二步完成: 先下达指令到浏览器, 再由浏览器完成 cookie 写入

4.演示代码

主页部分

  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" href="css/index.css" />
  7. <title>糗事百科</title>
  8. </head>
  9. <body>
  10. <header>
  11. <nav>
  12. <a href="">
  13. <img src="https://i.loli.net/2020/05/10/4yafTolzCbOnqiU.png" alt="" />
  14. </a>
  15. </nav>
  16. <nav>
  17. <a href="index.php">首页</a>
  18. <a href="">推荐</a>
  19. <a href="">图文</a>
  20. <a href="">视频</a>
  21. <a href="">论坛</a>
  22. </nav>
  23. <nav>
  24. <?php
  25. #####
  26. // 如果是session
  27. // 开启会话
  28. // session_start();
  29. // if (isset($_SESSION['user'])){
  30. // $session = unserialize($_SESSION['user']);
  31. // echo <<< AAA
  32. //<a href = "">欢迎你!{$session['username']} <img
  33. // src="https://pic.qiushibaike.com/system/avtnew/648/6480555/thumb/20200201071150.jpg"
  34. // alt=""
  35. // /></a>
  36. //<a href="" id="logout">退出</a>
  37. #####
  38. //判断是否登陆成功
  39. if (isset($_COOKIE['user'])){
  40. $cookie = unserialize($_COOKIE['user']);
  41. echo <<< AAA
  42. <a href = "">欢迎你!{$cookie['username']} <img
  43. src="https://pic.qiushibaike.com/system/avtnew/648/6480555/thumb/20200201071150.jpg"
  44. alt=""
  45. /></a>
  46. <a href="" id="logout">退出</a>
  47. AAA;
  48. }else{
  49. echo <<< BBB
  50. <a href="login.php">登录</a>
  51. <a href="register.php">注册</a>
  52. BBB;
  53. }
  54. ?>
  55. </nav>
  56. </header>
  57. <main>
  58. <section>
  59. <div>
  60. <img
  61. src="https://pic.qiushibaike.com/system/avtnew/648/6480555/thumb/20200201071150.jpg"
  62. alt=""
  63. /><span>旧梦雨伞</span>
  64. </div>
  65. <div>
  66. 有天晚上,和同事出去喝酒,先是用小酒杯,喝了几杯觉得不过瘾,
  67. 就叫老板拿大碗来,满满倒了一大碗,和同事一碰杯,一口干了。。
  68. 那次我醉得很厉害,一直到第二天下午才醒过来,还觉得晕头转向的,上厕所都是扶着墙去的!
  69. 同事来看我时,我看到同事两只眼睛都是乌黑的,吃了一惊:被谁揍了啊?告诉我,我帮你报
  70. 仇! 同事说:被你打的!你揍自己吧!!
  71. 我不信。同事说:你闹着要去找你前女友,我不让你去,所以……你不会真的一点印象都没有吧?
  72. 我。。。特么的,我咋一点都想不起来呢??
  73. </div>
  74. <div class="item1">
  75. <div>
  76. <a href="">好笑</a>
  77. <a href="">太low</a>
  78. <a href="">评论</a>
  79. </div>
  80. <div>
  81. 分享到
  82. <a href="">qq</a>
  83. <a href="">微信</a>
  84. <a href="">微博</a>
  85. </div>
  86. </div>
  87. <div>
  88. 神评
  89. <div>
  90. ,我不让你去,所以……你不会真的一点印象都没有吧?
  91. 我。。。特么的,我咋一点都想不起来呢??
  92. </div>
  93. </div>
  94. <hr />
  95. </section>
  96. <section>
  97. <div>
  98. <img
  99. src="https://pic.qiushibaike.com/system/avtnew/648/6480555/thumb/20200201071150.jpg"
  100. alt=""
  101. /><span>旧梦雨伞</span>
  102. </div>
  103. <div>
  104. 有天晚上,和同事出去喝酒,先是用小酒杯,喝了几杯觉得不过瘾,
  105. 就叫老板拿大碗来,满满倒了一大碗,和同事一碰杯,一口干了。。
  106. 那次我醉得很厉害,一直到第二天下午才醒过来,还觉得晕头转向的,上厕所都是扶着墙去的!
  107. 同事来看我时,我看到同事两只眼睛都是乌黑的,吃了一惊:被谁揍了啊?告诉我,我帮你报
  108. 仇! 同事说:被你打的!你揍自己吧!!
  109. 我不信。同事说:你闹着要去找你前女友,我不让你去,所以……你不会真的一点印象都没有吧?
  110. 我。。。特么的,我咋一点都想不起来呢??
  111. </div>
  112. <div class="item1">
  113. <div>
  114. <a href="">好笑</a>
  115. <a href="">太low</a>
  116. <a href="">评论</a>
  117. </div>
  118. <div>
  119. 分享到
  120. <a href="">qq</a>
  121. <a href="">微信</a>
  122. <a href="">微博</a>
  123. </div>
  124. </div>
  125. <div>
  126. 神评
  127. <div>
  128. ,我不让你去,所以……你不会真的一点印象都没有吧?
  129. 我。。。特么的,我咋一点都想不起来呢??
  130. </div>
  131. </div>
  132. </section>
  133. </main>
  134. <script>
  135. // 退出按钮监听
  136. document.querySelector('#logout').addEventListener('click',function (event) {
  137. if (confirm('是否退出')){
  138. // 禁用a跳转
  139. event.preventDefault();
  140. window.location.assign('handle.php?action=logout');
  141. }
  142. })
  143. </script>
  144. </body>
  145. </html>

处理器部分

  1. <?php
  2. #####
  3. //如果是session
  4. //开启会话
  5. //session_start();
  6. #####
  7. //先连接数据库
  8. $pdo = new PDO('mysql:host=localhost;dbname=php11.edu', 'php11.edu', 'php11.edu');
  9. $stmt = $pdo->prepare('SELECT * FROM `qb_users`');
  10. $stmt->execute();
  11. $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
  12. //处理用户登录
  13. @$action = $_GET['action'];
  14. if (@isset($action)) {
  15. switch (strtolower($action)) {
  16. // 登录
  17. case 'login':
  18. // 先判断请求是否合法
  19. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  20. // 开始验证
  21. // 获取需要验证的数据
  22. $email = $_POST['email'];
  23. $password = sha1($_POST['password']);
  24. $results = array_filter($users, function ($user) use ($email, $password) {
  25. return $user['email'] === $email && $user['password'] === $password;
  26. });
  27. if (count($results) === 1) {
  28. #####
  29. //如果是session
  30. //$_SESSION['user'] = serialize(array_pop($results));
  31. #####
  32. setcookie('user', serialize(array_pop($results)));
  33. die('<script> alert("登录成功");location.href="index.php"</script>');
  34. } else {
  35. die('<script> alert("账号或密码错误");location.href="login.php"</script>');
  36. }
  37. } else {
  38. die('请求非法');
  39. }
  40. break;
  41. // 退出
  42. case 'logout':
  43. if (isset($_COOKIE['user'])) {
  44. setcookie('user', null, time() - 3600);
  45. die('<script>alert("退出成功"); location.assign("index.php")</script>');
  46. }
  47. #####
  48. //如果是session
  49. // if (isset($_SESSION['username'])) {
  50. // session_destroy();
  51. // die('<script>alert("退出成功"); location.assign("index.php")</script>');
  52. // }
  53. #####
  54. break;
  55. //// 注册
  56. case 'register':
  57. /* @var string $username
  58. * @var string $p1
  59. * @var string $email
  60. * */
  61. extract($_POST);
  62. $p1 = sha1($p1);
  63. $register_time = time();
  64. //// 先检测一下数据库中有没有该邮箱如果有提示该邮箱已经注册
  65. $atmt = $pdo->prepare("SELECT `email` FROM `qb_users` WHERE `email` = '{$email}' ");
  66. $atmt->execute();
  67. $arr = $atmt->fetchAll(PDO::FETCH_ASSOC);
  68. if (empty($arr) === true) {
  69. // 如果是空则创建插入数据库
  70. $sql = "INSERT `qb_users` SET `username`='{$username}',`password` = '{$p1}',`email`='{$email}',`register_time` = '{$register_time}'";
  71. $stmt = $pdo->prepare($sql);
  72. $stmt->execute();
  73. // 检测一下
  74. if ($stmt->rowCount() === 1) {
  75. // 注册成功后创建cookie
  76. // 先查询到该条数据
  77. $stmt = $pdo->prepare('SELECT * FROM `qb_users`');
  78. $stmt->execute();
  79. $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
  80. $results = array_filter($users, function ($user) use ($email, $p1) {
  81. return $user['email'] === $email && $user['password'] === $p1;
  82. });
  83. // 序列化cookie返回
  84. //#####
  85. //如果是session
  86. //$_SESSION['user'] = serialize(array_pop($results));
  87. #####
  88. setcookie('user', serialize(array_pop($results)));
  89. die('<script>alert("注册成功!");location.assign("index.php")</script>');
  90. } else {
  91. die('<script>alert("注册失败!");location.assign("register.php")</script>');
  92. }
  93. } else {
  94. die('<script>alert("该邮箱已经注册过了,请直接登录");location.assign("login.php")</script>');
  95. }
  96. break;
  97. default:
  98. die('非法的操作');
  99. }
  100. }else{
  101. echo '请求非法';
  102. }

登录部分

  1. <?php
  2. //判断一下是否已经登陆
  3. if (isset($_COOKIE['user'])){
  4. die('<script>alert("请不要重复登录");location.href="index.php";</script>');
  5. }
  6. //如果是session
  7. //先开启会话
  8. //session_start();
  9. //if (isset($_SESSION['user'])){
  10. // die('<script>alert("请不要重复登录");location.href="index.php";</script>');
  11. //}
  12. //?>
  13. <!DOCTYPE html>
  14. <html lang="en">
  15. <head>
  16. <meta charset="UTF-8" />
  17. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  18. <link rel="stylesheet" href="css/style.css" />
  19. <title>用户登录</title>
  20. </head>
  21. <body>
  22. <main>
  23. <form action="handle.php?action=login" method="POST">
  24. <h3>用户登录</h3>
  25. <div>
  26. <label for="username">邮箱:</label>
  27. <input
  28. type="email"
  29. id="email"
  30. name="email"
  31. placeholder="请输入邮箱地址"
  32. required
  33. />
  34. </div>
  35. <div>
  36. <label for="password">密码:</label>
  37. <input
  38. type="password"
  39. id="password"
  40. name="password"
  41. placeholder="请输入密码"
  42. minlength="8"
  43. required
  44. />
  45. </div>
  46. <button>登录</button>
  47. <a href="register.php"><div>没有账号?点击注册</div> </a>
  48. </form>
  49. </main>
  50. </body>
  51. </html>

注册部分

  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" href="css/style.css" />
  7. <title>用户注册</title>
  8. </head>
  9. <body>
  10. <main>
  11. <form action="handle.php?action=register" method="post" onsubmit="return compare()">
  12. <h3>用户注册</h3>
  13. <div>
  14. <label for="username">昵称:</label>
  15. <input
  16. type="text"
  17. id="username"
  18. name="username"
  19. placeholder="请输入4-8位昵称"
  20. maxlength="8"
  21. required
  22. autofocus
  23. />
  24. </div>
  25. <div>
  26. <label for="email">邮箱:</label>
  27. <input
  28. type="email"
  29. id="email"
  30. name="email"
  31. placeholder="请输入邮箱地址"
  32. required
  33. autofocus
  34. />
  35. </div>
  36. <div>
  37. <label for="p1">密码:</label>
  38. <input
  39. type="password"
  40. id="p1"
  41. name="p1"
  42. placeholder="请输入8-16位密码"
  43. minlength="8"
  44. maxlength="16"
  45. required
  46. />
  47. </div>
  48. <div>
  49. <label for="p2">重复:</label>
  50. <input
  51. type="password"
  52. id="p2"
  53. name="p2"
  54. placeholder="重复输入密码"
  55. minlength="8"
  56. maxlength="16"
  57. required
  58. />
  59. </div>
  60. <button>注册</button><span id="tips"></span>
  61. <a href="login.php">
  62. <div>已有账号?去登录</div>
  63. </a>
  64. </form>
  65. </main>
  66. <script>
  67. function compare() {
  68. if (document.forms[0].p1.value.trim() !== document.forms[0].p2.value.trim()){
  69. alert('二次密码不相等');
  70. return false;
  71. }
  72. }
  73. </script>
  74. </body>
  75. </html>

index.css

  1. * {
  2. margin: 0px;
  3. padding: 0px;
  4. box-sizing: border-box;
  5. }
  6. body {
  7. min-width: 900px;
  8. }
  9. header {
  10. background-color: lightskyblue;
  11. display: flex;
  12. justify-content: space-around;
  13. align-items: center;
  14. }
  15. header > nav:first-child {
  16. height: 40px;
  17. }
  18. header > nav:first-of-type img {
  19. height: 100%;
  20. }
  21. header > nav:last-of-type img {
  22. border: none;
  23. height: 30px;
  24. border-radius: 50%;
  25. }
  26. header > nav > a {
  27. text-decoration: none;
  28. color: aliceblue;
  29. margin: 0px 20px;
  30. }
  31. header > nav > a:hover {
  32. color: lightcoral;
  33. }
  34. main {
  35. width: 50vw;
  36. margin: auto;
  37. display: flex;
  38. flex-flow: column nowrap;
  39. }
  40. main > section {
  41. margin-top: 15px;
  42. }
  43. main > section > div:first-of-type {
  44. height: 30px;
  45. display: flex;
  46. align-items: center;
  47. }
  48. main > section > div:first-of-type > img {
  49. height: 100%;
  50. border: none;
  51. border-radius: 50%;
  52. margin-right: 15px;
  53. }
  54. main > section > div:first-of-type > span {
  55. font-size: 0.8rem;
  56. color: slategray;
  57. }
  58. main > section > div:nth-of-type(2) {
  59. margin-top: 10px;
  60. text-indent: 20px;
  61. line-height: 20px;
  62. font-size: 0.9rem;
  63. color: saddlebrown;
  64. }
  65. .item1 {
  66. margin: 15px 0px;
  67. display: flex;
  68. justify-content: space-between;
  69. }
  70. .item1 a {
  71. padding: 2px 8px;
  72. text-decoration: none;
  73. background-color: lightblue;
  74. border: none;
  75. border-radius: 5px;
  76. font-size: 0.8rem;
  77. }
  78. .item1 > div:last-of-type {
  79. font-size: 0.8rem;
  80. color: violet;
  81. }
  82. section > div:last-of-type {
  83. color: red;
  84. display: flex;
  85. margin-bottom: 20px;
  86. }
  87. section > div:last-of-type div {
  88. padding: 3px 5px;
  89. margin-left: 10px;
  90. width: 80%;
  91. border: 1px solid lavender;
  92. color: chocolate;
  93. font-size: 0.8rem;
  94. }
  95. hr {
  96. color: lightcyan;
  97. }

style.css

  1. * {
  2. margin: 0px;
  3. padding: 0px;
  4. box-sizing: border-box;
  5. }
  6. body {
  7. background-color: lightcyan;
  8. }
  9. main {
  10. margin: 100px auto;
  11. width: 300px;
  12. padding: 20px;
  13. border: none;
  14. border-radius: 20px;
  15. background-color: lightskyblue;
  16. text-align: center;
  17. }
  18. main div {
  19. margin: 15px 0px;
  20. }
  21. button {
  22. padding: 5px 30px;
  23. width: 100px;
  24. border: none;
  25. border-radius: 10px;
  26. }
  27. button:hover {
  28. background-color: lightgreen;
  29. }
  30. a {
  31. text-decoration: none;
  32. font-size: 0.8rem;
  33. color: crimson;
  34. }
  35. a:hover {
  36. color: aliceblue;
  37. }

总结

没学会话控制之前感觉这个一定很难,学会之后发现简直不要太简单!

Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:本来就挺简单的, 之前是自己吓自己... 觉得简单, 有二个原因, 一是你很聪明, 二是教的...
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post