Blogger Information
Blog 48
fans 3
comment 1
visits 30286
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
使用session会话来实现登录注册案例
吴长清
Original
446 people have browsed it

index.php 入口文件

  1. <?php
  2. namespace login;
  3. // 开启会话
  4. session_start();
  5. // 判断是否已登录?
  6. if (isset($_SESSION['user'])) {
  7. // 反序列化
  8. $user = unserialize($_SESSION['user']);
  9. }
  10. ?>
  11. <!DOCTYPE html>
  12. <html lang="zh-CN">
  13. <head>
  14. <meta charset="UTF-8">
  15. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  16. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  17. <title>首页/入口文件</title>
  18. <style>
  19. nav {
  20. height: 40px;
  21. background-color: deepskyblue;
  22. padding: 0 20px;
  23. display: flex;
  24. justify-content: space-between;
  25. align-items: center;
  26. }
  27. nav .loginbox {
  28. display: flex;
  29. padding: 0 20px;
  30. justify-content: space-between;
  31. align-items: center;
  32. gap: 0px 20px;
  33. }
  34. nav .loginbox>a,
  35. nav .loginbox>span {
  36. color: white;
  37. text-decoration: none;
  38. }
  39. nav .loginbox>span {
  40. font-weight: bold;
  41. }
  42. nav .loginbox>a:hover {
  43. cursor: pointer;
  44. }
  45. </style>
  46. </head>
  47. <body>
  48. <nav>
  49. <a href="index.php">我的博客</a>
  50. <div class="loginbox">
  51. <?php if (isset($user)) : ?>
  52. <span>用户昵称: <?= $user[0]['name'] ?></span>
  53. <span>用户性别: <?= $user[0]['sex'] ? '女' : '男' ?></span>
  54. <a id="logout">退出</a>
  55. <?php else : ?>
  56. <a href="login.php">登录</a>
  57. <?php endif ?>
  58. </div>
  59. </nav>
  60. <script>
  61. // 为退出按钮创建事件监听器
  62. document.querySelector('#logout').addEventListener('click', function(event) {
  63. if (confirm('是否退出')) {
  64. // 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
  65. event.preventDefault();
  66. // 跳转到退出事件处理器
  67. window.location.assign('handle.php?action=logout');
  68. }
  69. });
  70. </script>
  71. </body>
  72. </html>

login.php 登录界面

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>用户登录</title>
  6. <style>
  7. body {
  8. background: linear-gradient(100deg, white, #00d5ff)
  9. }
  10. fieldset {
  11. width: 300px;
  12. background: linear-gradient(100deg, #00d5ff, #00aaff);
  13. margin: 200px auto;
  14. }
  15. legend {
  16. background-color: white;
  17. margin: auto;
  18. font-size: larger;
  19. }
  20. fieldset>div {
  21. width: 240px;
  22. margin: auto;
  23. padding: 10px;
  24. }
  25. fieldset>div form div {
  26. margin-top: 5px;
  27. }
  28. button {
  29. width: 80px;
  30. }
  31. button:hover {
  32. cursor: pointer;
  33. }
  34. </style>
  35. </head>
  36. <body>
  37. <fieldset>
  38. <legend>用户登录</legend>
  39. <div>
  40. <form action="handle.php?action=login" method="post">
  41. <div>
  42. <label for="email">邮箱:</label>
  43. <input type="email" name="email" id="email" placeholder="demo@email.com" required autofocus>
  44. </div>
  45. <div>
  46. <label for="password">密码:</label>
  47. <input type="password" name="password" id="password" placeholder="不少于6位" required>
  48. </div>
  49. <div>
  50. <button>提交</button>
  51. </div>
  52. </form>
  53. <a href="register.php">还没有帐号, 注册一个吧</a>
  54. </div>
  55. </fieldset>
  56. </body>
  57. </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. <!-- <link rel="stylesheet" type="text/css" href="css/style.css"> -->
  7. <title>注册用户</title>
  8. <style>
  9. body {
  10. background: linear-gradient(100deg, white, #00d5ff)
  11. }
  12. fieldset {
  13. width: 300px;
  14. background: linear-gradient(100deg, #00d5ff, #00aaff);
  15. margin: 200px auto;
  16. }
  17. legend {
  18. background-color: white;
  19. margin: auto;
  20. font-size: larger;
  21. }
  22. fieldset>div {
  23. width: 240px;
  24. margin: auto;
  25. padding: 10px;
  26. }
  27. fieldset>div form div {
  28. margin-top: 5px;
  29. }
  30. button {
  31. width: 80px;
  32. }
  33. button:hover {
  34. cursor: pointer;
  35. }
  36. </style>
  37. </head>
  38. <body>
  39. <fieldset>
  40. <legend>用户注册</legend>
  41. <div>
  42. <form action="handle.php?action=register" method="post" onsubmit="return compare()">
  43. <div>
  44. <label for="name">呢称:</label>
  45. <input type="text" name="name" id="name" placeholder="不少于3个字符" required autofocus>
  46. </div>
  47. <div>
  48. <label for="email">邮箱:</label>
  49. <input type="email" name="email" id="email" placeholder="demo@email.com" required>
  50. </div>
  51. <div>
  52. <label for="p1">密码:</label>
  53. <input type="password" name="p1" id="p1" placeholder="不少于6位" required>
  54. </div>
  55. <div>
  56. <label for="p2">重复:</label>
  57. <input type="password" name="p2" id="p2" placeholder="必须与上面一致" required>
  58. </div>
  59. <div>
  60. <button>提交</button><span id="tips" style="color: red"></span>
  61. </div>
  62. </form>
  63. <a href="login.php">我有帐号,直接登录</a>
  64. </div>
  65. </fieldset>
  66. <script>
  67. // 验证二次密码是否相等?
  68. function compare() {
  69. if (document.forms[0].p1.value.trim() !== document.forms[0].p2.value.trim()) {
  70. document.querySelector('#tips').innerText = '二次密码不相等';
  71. return false;
  72. }
  73. }
  74. </script>
  75. </body>
  76. </html>

handle.php 会话处理控制器

  1. <?php
  2. /**
  3. * 会话处理控制器
  4. * 处理登录、注册、退出操作
  5. */
  6. namespace headerController;
  7. use PDO;
  8. // 开启会话:必须写在最前面
  9. session_start();
  10. // 查询用书表中的数据user表
  11. $db = new PDO('mysql:dbname=phpedu', 'root', 'root');
  12. $stmt = $db->prepare('SELECT * FROM `user`;');
  13. $stmt->execute();
  14. // 得到所有用户数据
  15. $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
  16. //print_r($users);
  17. // 获取用户操作类型 login/register/logout
  18. // strtolower 转小写
  19. $action = strtolower($_GET['action']);
  20. // 根据类型进行不同的操作
  21. switch ($action) {
  22. // 1.登录
  23. case 'login':
  24. // 检查请求方式的类型
  25. if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  26. // 获取用户请求的数据:邮箱和密码
  27. $email = $_POST['email'];
  28. // sha1() 加密函数 返回长度为40的字符串
  29. $password = sha1($_POST['password']);
  30. // array_filter 过滤用户数据,在数据表中查找$email和$password,有,返回结果集,没有返回false
  31. $result = array_filter($users, function ($user) use ($email, $password) {
  32. return $user['email'] === $email && $user['password'] === $password;
  33. });
  34. // print_r($result);
  35. // die;
  36. // 判断 $result 是否有数据
  37. if (count($result) > 1) {
  38. // 将用户信息通过session保存serialize序列化后的数据到服务器上
  39. $_SESSION['user'] = serialize(array_slice($result, 0));
  40. exit('<script>alert("验证通过");location.href="index.php"</script>');
  41. } else {
  42. // 登录失败 提示用户未注册
  43. exit("<script>alert('登录失败,邮箱: " . $email . "未注册');location.href='login.php'</script>");
  44. }
  45. } else {
  46. exit('请求类型错误');
  47. }
  48. // 2.退出
  49. case 'logout':
  50. // 判断session数据是否为空
  51. if (isset($_SESSION['user'])) {
  52. // 销毁session 连文件一起删除
  53. session_destroy();
  54. exit('<script>alert("退出成功");location.href="index.php"</script>');
  55. } else {
  56. exit('系统错误, session不存在');
  57. }
  58. // 3.注册
  59. case 'register':
  60. // 获取新用户的数据
  61. $email = $_POST['email'];
  62. $name = $_POST['name'];
  63. $password = sha1($_POST['p2']);
  64. $register_data = time();
  65. // 检查邮箱是否存在
  66. $result = array_filter($users, function ($user) use ($email) {
  67. return $user['email'] === $email;
  68. });
  69. print_r(count($result));
  70. // 判断邮箱是否已注册
  71. if (count($result) > 1) {
  72. exit("<script>alert('注册失败,邮箱: " . $email . "已注册');location.href='register.php'</script>");
  73. } else {
  74. $sql = <<< SQL
  75. INSERT `user`
  76. SET `name`= ?,
  77. `email`= ?,
  78. `password`= ?,
  79. `register_data`= ?
  80. SQL;
  81. // 查询新用户信息
  82. $stmt = $db->prepare($sql);
  83. $data = [$name, $email, $password, $register_data];
  84. if ($stmt->execute($data)) {
  85. if ($stmt->rowCount() > 0) {
  86. // 注册成功之后,让用户自动登录
  87. $sql = 'SELECT * FROM `user` WHERE `id` = ' . $db->lastInsertId();
  88. $stmt = $db->prepare($sql);
  89. $stmt->execute();
  90. $newUser = $stmt->fetchAll(PDO::FETCH_ASSOC);
  91. // 序列化 保存到session
  92. $_SESSION['user'] = serialize($newUser);
  93. exit('<script>alert("注册成功");location.href="index.php"</script>');
  94. } else {
  95. exit('<script>alert("注册失败");location.href="register.php"</script>');
  96. }
  97. } else {
  98. // 输出sql执行错误信息
  99. print_r($stmt->errorInfo());
  100. }
  101. }
  102. default:
  103. // 提示消息后结束执行
  104. exit('参数非法或未定义操作');
  105. }

效果预览

Correcting teacher:PHPzPHPz

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