Blogger Information
Blog 94
fans 0
comment 0
visits 92448
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【PHP】用户管理器/登录/注册/退出 [整合版]
可乐随笔
Original
2512 people have browsed it

用户管理器/登录/注册/退出 [整合版]

带类型的请求:
如:serHandle.php?action=login

  1. <?php
  2. // 用户管理器/登录/注册/退出
  3. // 1.开启会话
  4. session_start();
  5. // 2. 加载用户数据
  6. require __DIR__ . '/../config/common.php';
  7. $users = require DATA_PATH . '/users.php';
  8. // 3. 获取get请求参数
  9. $action = strtolower($_GET['action']);
  10. // 4. 操作白名单
  11. $allowOpts = ['login','register', 'logout'];
  12. // 5. 操作结果默认值
  13. $prompt = false;
  14. // 6. 检测操作类型是否合法?
  15. if (!in_array($action, $allowOpts)) {
  16. echo <<< TIPS
  17. <script>
  18. alert('操作类型非法');
  19. location.href='../login.php';
  20. </script>
  21. TIPS;
  22. die;
  23. }
  24. // 7. 判断要做什么
  25. switch ($action) {
  26. // 7.1 登录
  27. case 'login':
  28. // 获取json,转array
  29. $json = file_get_contents('php://input');
  30. $user = json_decode($json, true);
  31. $email = $user['email'];
  32. $password = md5($user['password']);
  33. $result = array_filter($users, function ($user) use ($email, $password) {
  34. return $user['email'] === $email && $user['password'] === $password;
  35. });
  36. if (count($result) === 1) {
  37. $prompt = true;
  38. // 登录成功,将用户信息写入session
  39. $_SESSION['user'] = array_pop($result);
  40. }
  41. break;
  42. // 7.2. 注册
  43. case 'register':
  44. $oriCount = count($users);
  45. $json = file_get_contents('php://input');
  46. $user = json_decode($json, true);
  47. $user['password'] = md5($user['password']);
  48. $user['id'] = count($users)+1;
  49. $users[] = $user;
  50. if (count($users) === $oriCount + 1) {
  51. $prompt = true;
  52. }
  53. break;
  54. // 7.3 退出
  55. case 'logout':
  56. if (session_destroy()) {
  57. $prompt = true;
  58. }
  59. break;
  60. }
  61. // 8. 结果返回前端
  62. echo json_encode($prompt);
  63. die;
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