Blogger Information
Blog 28
fans 0
comment 0
visits 21990
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php:会话控制
暝皑祯π_π
Original
985 people have browsed it

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. <title>首页</title>
  13. <style>
  14. nav {
  15. height: 40px;
  16. padding: 0 15px;
  17. background-color: black;
  18. display: flex;
  19. justify-content: space-between;
  20. align-items: center;
  21. }
  22. a {
  23. font-size: 20px;
  24. color: white;
  25. text-decoration: none;
  26. }
  27. </style>
  28. </head>
  29. <body>
  30. <nav>
  31. <a href="index.php">首页</a>
  32. <?php if (isset($user)) : ?>
  33. <a href="" id="logout"><span style="color:red"><?php echo $user['name']?></span> 退出</a>
  34. <?php else: ?>
  35. <a href="login.php">登录</a>
  36. <?php endif ?>
  37. </nav>
  38. </body>
  39. <script>
  40. // 为退出按钮创建事件监听器
  41. document.querySelector('#logout').addEventListener('click', function(event) {
  42. if (confirm('是否退出')) {
  43. // 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
  44. event.preventDefault();
  45. // 跳转到退出事件处理器
  46. window.location.assign('handle.php?action=logout');
  47. }
  48. });
  49. </script>
  50. </html>

login.php

  1. <?php
  2. session_start();
  3. // 判断是否已登录
  4. if (isset($_SESSION['user']))
  5. exit('<script>alert("请不要重复登录");location.href="index.php";</script>');
  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. <title>登录</title>
  13. <link rel="stylesheet" href="index.css/index.css">
  14. </head>
  15. <body>
  16. <h3>用户登录</h3>
  17. <form action="handle.php?action=login" method="POST">
  18. <div>
  19. <label for="email">邮箱:</label>
  20. <input type="email" name="email" id="email" placeholder="@qq.com" require autofocus>
  21. </div>
  22. <div>
  23. <label for="password">密码:</label>
  24. <input type="password" name="password" id="password" placeholder="不小于6位">
  25. </div>
  26. <div>
  27. <button>登录</button>
  28. </div>
  29. </form>
  30. <a href="register.php">注册</a>
  31. </body>
  32. </html>

register.php

  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. <title>用户注册</title>
  7. <link rel="stylesheet" href="index.css/index.css">
  8. </head>
  9. <body>
  10. <h3>用户注册</h3>
  11. <form action="handle.php?action=register" method="POST">
  12. <div>
  13. <label for="name">昵称:</label>
  14. <input type="text" name="name" id="name" require placeholder="昵称" autofocus>
  15. </div>
  16. <div>
  17. <label for="email">邮箱:</label>
  18. <input type="email" name="email" id="email" require placeholder="@qq.com">
  19. </div>
  20. <div>
  21. <label for="password">密码:</label>
  22. <input type="password" name="password" id="password" require placeholder="不少于6位">
  23. </div>
  24. <div>
  25. <label for="password">重复:</label>
  26. <input type="password" name="password" id="password" require placeholder="必须与上面密码一致">
  27. </div>
  28. <div>
  29. <button>注册</button>
  30. </div>
  31. </form>
  32. <a href="login.php">登录</a>
  33. </body>
  34. </html>

handle.php

  1. <?php
  2. // 开启会话
  3. session_start();
  4. // 连接数据库
  5. $pdo = new PDO('mysql:host=php.cn;dbname=php','root','root');
  6. $stmt = $pdo->prepare("SELECT * FROM `users`");
  7. $stmt->execute();
  8. $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
  9. // print_r($a);
  10. // 处理用户登录与注册
  11. $action = $_GET['action']; //获取get参数`login`或者是`register`
  12. // 判断用户是想登录(login)或者是注册(register)
  13. // strtolower:把字符串转换为小写
  14. switch(strtolower($action)){
  15. // 登录
  16. case 'login':
  17. // 判断请求是否合法
  18. // $_SERVER['REQUEST_METHOD']:请求类型
  19. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  20. // 请求正确 ,获取需要验证的数据
  21. $email = $_POST['email'];
  22. $password = sha1($_POST['password']);
  23. // 用回调函数过滤数组中的元素,返回数组中email和passeord和当前用户输入的数据相同的值
  24. // $users:数据库中的数据
  25. // $user:$users数组中的每个键值对,也叫用户的所有信息
  26. $results = array_filter($users, function($user) use ($email, $password) {
  27. return $user['email'] === $email && $user['password'] === $password;
  28. });
  29. // count:计算数组的单元数目
  30. // 如果results === 1;说明用户存在
  31. if (count($results) === 1) {
  32. // unseralize:反序列化
  33. // seralize:序列化
  34. // array_pop:删除数组中最后一个元素;出栈
  35. // user的值等于序列化后的$resylts中的最后一个元素
  36. // 设置session
  37. $_SESSION['user'] = serialize(array_pop($results));
  38. exit('<script>alert("验证通过");location.href="index.php"</script>');
  39. } else {
  40. exit('<script>alert("邮箱或密码错误,或者还没有帐号");location.href="login.php";</script>');
  41. }
  42. }else{
  43. die('请求错误');
  44. }
  45. break;
  46. // 退出
  47. case 'logout':
  48. if (isset($_SESSION['user'])) {
  49. // 注销所有session变量,并且结束session会话
  50. session_destroy();
  51. exit('<script>alert("退出成功");php.cn.assign("index.php")</script>');
  52. }
  53. break;
  54. case'register':
  55. // 注册
  56. // 获取数据
  57. $name = $_POST['name'];
  58. $email = $_POST['email'];
  59. $password = sha1($_POST['password']);
  60. $register_time =time();
  61. // 将新用户插入到表中
  62. $sql = "INSERT `users` SET `name`='{$name}', `email`='{$email}', `password`='{$password}', `register_time`={$register_time}";
  63. $stmt = $pdo->prepare($sql);
  64. $stmt->execute();
  65. // 变量不能放在数组中
  66. // $stmt->execute([$name,$email,$password,$time]);
  67. // stmt->rowcount:返回受上一个sql语句影响的行数
  68. // 如果stmt->rowcount:返回受上一个sql语句影响的行数 === 1,说明插入成功
  69. if ($stmt->rowCount() === 1) exit('<script>alert("注册成功");php.cn.assign("login.php")</script>');
  70. else exit('<script>alert("注册失败");php.cn.assign("login.php")</script>');
  71. break;
  72. // 未定义
  73. default:
  74. exit('未定义操作');
  75. }

总结

  • session:需要开启会话:session_strat()cookin不需要
  • 会话控制原理:
    • 通过urlaction信息,判断用户想要执行的操作
      • 登录:
        1. 1.判断数据请求是否正确
        2. 2. 获取用户输入的信息与`session`中的信息匹配,成功则登录,不成功则输出错误提示。
      • 退出:
        1. 1. session_destroy():注销所有session变量,并且结束session会话
      • 注册:
        1. 1. 通过`$_POST`获取用户信息
        2. 2.使用数据库新增的方法把用户信息添加到数据库
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