Blogger Information
Blog 32
fans 2
comment 2
visits 23240
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
cookie和session实现登录验证(0114)
暴风战斧
Original
560 people have browsed it

编程思路

1、我首先把登录验证整个流程画了出来;
2、考虑到请求验证分发页会花较多时间,将上次做的登录页拿来做了修改,快速完成了首页、登录、注册页;
3、然后写请求验证分发页,重点是将登录>注册>退出,挨个一边写一边查看效果修改代码!

作业总结

这次作业对过滤器的使用要顺心很多了,在两个地方有卡壳,一是:action=”handle.php?action=login”漏掉了action=,导致switch一直无法启用反复查看才发现;二是:array_filter()函数和里面的function($user)没理解,回看视频并结合手册解释“该函数把输入数组中的每个键值传给回调函数。如果回调函数返回 true,则把输入数组中的当前键值返回给结果数组。数组键名保持不变。”才顺利理解了!

  1. array_filter($users, function ($user) use ($email, $password) {
  2. return $email === $user['email'] && $password === $user['password'];
  3. }

1.登录验证流程图

  • 首页代码
  1. <?php
  2. //首页
  3. //判断是否登录
  4. if (filter_has_var(INPUT_COOKIE,'user')) {
  5. $user = unserialize(filter_input(INPUT_COOKIE,'user'));
  6. }
  7. //print_r($user);
  8. ?>
  9. <!doctype html>
  10. <html lang="en">
  11. <head>
  12. <meta charset="UTF-8">
  13. <title>首页</title>
  14. <link rel="stylesheet" href="index.css">
  15. </head>
  16. <body>
  17. <div>
  18. <a href="">在线商城</a>
  19. <!--登录状态判断-->
  20. <?php if (isset($user)) : ?>
  21. <a href="" id="logout">
  22. <span><?php echo $user['name'] ?></span>
  23. 退出
  24. </a>
  25. <?php else : ?>
  26. <a href="login.php">登录</a>
  27. <?php endif ?>
  28. </div>
  29. <script>
  30. // 为退出按钮创建事件监听器
  31. if (document.querySelector('#logout') !== null) {
  32. document.querySelector('#logout').addEventListener('click', function(event) {
  33. if (confirm('是否退出')) {
  34. // 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
  35. event.preventDefault();
  36. // 跳转到退出事件处理器
  37. window.location.assign('handle.php?action=logout');
  38. }
  39. });
  40. }
  41. </script>
  42. </body>
  43. </html>
  • 登录页代码
  1. <?php
  2. //检查是否重复登录
  3. if (filter_input(INPUT_COOKIE, 'user')) {
  4. exit('<script>alert("请不要重复登录")</script>');
  5. }
  6. ?>
  7. <!doctype html>
  8. <html lang="en">
  9. <head>
  10. <meta charset="UTF-8">
  11. <title>用户登录</title>
  12. <link rel="stylesheet" href="style.css">
  13. </head>
  14. <body>
  15. <div class="container">
  16. <h3>用户登录</h3>
  17. <form action="handle.php?action=login" method="post">
  18. <span>
  19. <label for="email">邮箱:</label>
  20. <input type="email" name="email" id="email" placeholder="demo@php.cn" required autofocus>
  21. </span>
  22. <span>
  23. <label for="password">密码:</label>
  24. <input type="password" name="password" id="password" placeholder="请输入密码" required autofocus>
  25. </span>
  26. <span>
  27. <button>立即登录</button>
  28. </span>
  29. </form>
  30. <div>
  31. <a href="register.php">还没账号,注册一个!</a>
  32. </div>
  33. </div>
  34. </body>
  35. </html>
  • 效果图

  • 注册页代码
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>用户注册</title>
  6. <link rel="stylesheet" href="style.css">
  7. </head>
  8. <body>
  9. <div class="container">
  10. <h3>用户注册</h3>
  11. <form action="handle.php?action=register" method="post" onsubmit="return compare()">
  12. <span>
  13. <label for="name">昵称:</label>
  14. <input type="text" name="name" id="name" placeholder="昵称不少于3个字符" required autofocus>
  15. </span>
  16. <span>
  17. <label for="email">邮箱:</label>
  18. <input type="email" name="email" id="email" placeholder="demo@php.cn" required autofocus>
  19. </span>
  20. <span>
  21. <label for="p1">密码:</label>
  22. <input type="password" name="p1" id="p1" placeholder="请输入密码" required>
  23. </span>
  24. <span>
  25. <label for="p2">重复:</label>
  26. <input type="password" name="p2" id="p2" placeholder="再次输入密码" required>
  27. </span>
  28. <span>
  29. <button>立即注册</button>
  30. <span id="tips" style="color: red"></span>
  31. </span>
  32. </form>
  33. <div>
  34. <a href="login.php">我有账号,直接登录!</a>
  35. </div>
  36. </div>
  37. <script>
  38. // 验证二次密码是否相等?
  39. function compare() {
  40. if (document.forms[0].p1.value.trim() !== document.forms[0].p2.value.trim()) {
  41. document.querySelector('#tips').innerText = '二次密码不相等';
  42. return false;
  43. }
  44. }
  45. </script>
  46. </body>
  47. </html>
  • 效果图

  • 请求分发页代码
  1. <?php
  2. // 用户资料
  3. $users = [
  4. [
  5. 'id' => 1,
  6. 'name' => 'admin',
  7. 'email' => 'admin@php.cn',
  8. 'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
  9. ],
  10. [
  11. 'id' => 2,
  12. 'name' => 'peter',
  13. 'email' => 'peter@php.cn',
  14. 'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
  15. ],
  16. ];
  17. //1、验证请求来源合法性
  18. //合法的请求URL白名单
  19. $allowUrls = ['login.php', 'register.php', 'index.php'];
  20. //获取当前请求的入口地址
  21. $currentUrl = basename(filter_input(INPUT_SERVER, 'HTTP_REFERER'));
  22. //echo $currentUrl;
  23. //验证来源合法性
  24. if (!in_array($currentUrl, $allowUrls)) {
  25. exit('非法来源');
  26. }
  27. //2、请求的分发处理
  28. //获取到当前请求类型
  29. $action = filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
  30. $action = strtolower($action);
  31. //echo $action;
  32. //分发处理
  33. switch ($action) {
  34. //登录
  35. case 'login':
  36. //(1)验证登录请求合法性
  37. if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') {
  38. //(2)获取当前请求数据
  39. $email = filter_var(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL), FILTER_SANITIZE_EMAIL);
  40. $password = sha1(filter_input(INPUT_POST, 'password'));
  41. // echo $email, $password;
  42. $results = array_filter($users, function ($user) use ($email, $password) {
  43. return $email === $user['email'] && $password === $user['password'];
  44. });
  45. // print_r($results);
  46. if (count($results) === 1) {
  47. setcookie('user', serialize(array_pop($results)));
  48. exit('<script>alert("登录成功");location.href="index.php"</script>');
  49. } else {
  50. exit('<script>alert("邮箱或密码错误,或没有账号!");location.href="register.php"</script>');
  51. }
  52. } else {
  53. exit('请求非法');
  54. }
  55. break;
  56. //退出
  57. case 'logout':
  58. //检查cookie中是否有该用户,有则删除cookie
  59. if (filter_input(INPUT_COOKIE, 'user')) {
  60. setcookie('user', null, time() - 3600);
  61. exit('<script>alert("退出成功");location.href="index.php"</script>');
  62. }
  63. break;
  64. //注册
  65. case 'register':
  66. //处理注册信息
  67. if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') {
  68. //获取注册信息
  69. $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
  70. $email = filter_var(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL), FILTER_SANITIZE_EMAIL);
  71. $password = sha1(filter_input(INPUT_POST, 'password'));
  72. $id = 3;
  73. //打包注册信息
  74. $data = compact($name, $email, $password, $id);
  75. //注册信息写入资料库并提示
  76. if (array_push($users, $data)) {
  77. exit('<script>alert("注册成功");location.assign("index.php")</script>');
  78. }
  79. }
  80. break;
  81. //未定义操作
  82. default:
  83. exit('未定义的操作');
  84. }

3.session实现登录验证

  • 首页代码
  1. <?php
  2. //开启会话
  3. session_start();
  4. //判断是否登录
  5. //if (filter_has_var(INPUT_COOKIE,'user')) {
  6. // $user = unserialize(filter_input(INPUT_COOKIE,'user'));
  7. //}
  8. //print_r($user);
  9. if (isset($_SESSION['user'])) {
  10. $user = $_SESSION['user'];
  11. }
  12. ?>
  13. <!doctype html>
  14. <html lang="en">
  15. <head>
  16. <meta charset="UTF-8">
  17. <title>首页</title>
  18. <link rel="stylesheet" href="../index.css">
  19. </head>
  20. <body>
  21. <div>
  22. <a href="">在线商城</a>
  23. <!--登录状态判断-->
  24. <?php if (isset($user)) : ?>
  25. <a href="" id="logout">
  26. <span><?php echo $user['name'] ?></span>
  27. 退出
  28. </a>
  29. <?php else : ?>
  30. <a href="login.php">登录</a>
  31. <?php endif ?>
  32. </div>
  33. <script>
  34. // 为退出按钮创建事件监听器
  35. if (document.querySelector('#logout') !== null) {
  36. document.querySelector('#logout').addEventListener('click', function(event) {
  37. if (confirm('是否退出')) {
  38. // 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
  39. event.preventDefault();
  40. // 跳转到退出事件处理器
  41. window.location.assign('handle.php?action=logout');
  42. }
  43. });
  44. }
  45. </script>
  46. </body>
  47. </html>
  • 登录页代码
  1. <?php
  2. //开启会话
  3. session_start();
  4. //检查是否重复登录
  5. if (isset($_SESSION['user'])) {
  6. exit('<script>alert("请不要重复登录")</script>');
  7. }
  8. ?>
  9. <!doctype html>
  10. <html lang="en">
  11. <head>
  12. <meta charset="UTF-8">
  13. <title>用户登录</title>
  14. <link rel="stylesheet" href="../style.css">
  15. </head>
  16. <body>
  17. <div class="container">
  18. <h3>用户登录</h3>
  19. <form action="handle.php?action=login" method="post">
  20. <span>
  21. <label for="email">邮箱:</label>
  22. <input type="email" name="email" id="email" placeholder="demo@php.cn" required autofocus>
  23. </span>
  24. <span>
  25. <label for="password">密码:</label>
  26. <input type="password" name="password" id="password" placeholder="请输入密码" required autofocus>
  27. </span>
  28. <span>
  29. <button>立即登录</button>
  30. </span>
  31. </form>
  32. <div>
  33. <a href="register.php">还没账号,注册一个!</a>
  34. </div>
  35. </div>
  36. </body>
  37. </html>
  • 请求分发页代码
  1. <?php
  2. //开启会话
  3. session_start();
  4. // 用户资料
  5. $users = [
  6. [
  7. 'id' => 1,
  8. 'name' => 'admin',
  9. 'email' => 'admin@php.cn',
  10. 'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
  11. ],
  12. [
  13. 'id' => 2,
  14. 'name' => 'peter',
  15. 'email' => 'peter@php.cn',
  16. 'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
  17. ],
  18. [
  19. 'id' => 4,
  20. 'name' => 'wener',
  21. 'email' => 'wener@php.cn',
  22. 'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
  23. ]
  24. ];
  25. //1、验证请求来源合法性
  26. //合法的请求URL白名单
  27. $allowUrls = ['login.php', 'register.php', 'index.php'];
  28. //获取当前请求的入口地址
  29. $currentUrl = basename(filter_input(INPUT_SERVER, 'HTTP_REFERER'));
  30. //echo $currentUrl;
  31. //验证来源合法性
  32. if (!in_array($currentUrl, $allowUrls)) {
  33. exit('非法来源');
  34. }
  35. //2、请求的分发处理
  36. //获取到当前请求类型
  37. $action = filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
  38. $action = strtolower($action);
  39. //echo $action;
  40. //分发处理
  41. switch ($action) {
  42. //登录
  43. case 'login':
  44. //(1)验证登录请求合法性
  45. if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') {
  46. //(2)获取当前请求数据
  47. $email = filter_var(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL), FILTER_SANITIZE_EMAIL);
  48. $password = sha1(filter_input(INPUT_POST, 'password'));
  49. // echo $email, $password;
  50. $results = array_filter($users, function ($user) use ($email, $password) {
  51. return $email === $user['email'] && $password === $user['password'];
  52. });
  53. // print_r($results);
  54. if (count($results) === 1) {
  55. $_SESSION['user'] = array_pop($results);
  56. exit('<script>alert("登录成功");location.href="index.php"</script>');
  57. } else {
  58. exit('<script>alert("邮箱或密码错误,或没有账号!");location.href="register.php"</script>');
  59. }
  60. } else {
  61. exit('请求非法');
  62. }
  63. break;
  64. //退出
  65. case 'logout':
  66. //检查是否有该用户,有则删除
  67. if (isset($_SESSION['user'])) {
  68. session_destroy();
  69. exit('<script>alert("退出成功");location.href="index.php"</script>');
  70. }
  71. break;
  72. //注册
  73. case 'register':
  74. //处理注册信息
  75. if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') {
  76. //获取注册信息
  77. $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
  78. $email = filter_var(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL), FILTER_SANITIZE_EMAIL);
  79. $password = sha1(filter_input(INPUT_POST, 'password'));
  80. $id = 3;
  81. //打包注册信息
  82. $data = compact($name, $email, $password, $id);
  83. //注册信息写入资料库并提示
  84. if (array_push($users, $data)) {
  85. exit('<script>alert("注册成功");location.assign("index.php")</script>');
  86. }
  87. }
  88. break;
  89. //未定义操作
  90. default:
  91. exit('未定义的操作');
  92. }
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