欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

将请求分发器的注册与退出登录完善

程序员文章站 2022-03-07 18:11:36
...
  1. <?php
  2. session_start();
  3. //连接数据库
  4. require '1-connect.php';
  5. // 接受前端传过来的参数
  6. $name = isset($_POST['uname']) ? $_POST['uname'] : null;
  7. $pwd = isset($_POST['pwd']) ? $_POST['pwd'] : null;
  8. $gender = isset($_POST['gender']) ? $_POST['gender'] : null;
  9. $created_at = time();
  10. $type = strtolower($_GET['type']);
  11. // 请求分发器 注册 登录 退出
  12. switch ($type) {
  13. case 'login':
  14. $res = loginCheck($name, $pwd);
  15. if ($res) {
  16. echo json_encode(['status' => 1, 'msg' => '登录成功'], 320);
  17. exit;
  18. }
  19. echo json_encode(['status' => 0, 'msg' => '用户名或密码错误'], 320);
  20. break;
  21. case 'reg':
  22. $res = insertData($name, $pwd, $gender, $created_at);
  23. if ($res) {
  24. echo json_encode(['status' => 1, 'msg' => '注册成功'], 320);
  25. exit;
  26. }
  27. echo json_encode(['status' => 0, 'msg' => '注册失败'], 320);
  28. break;
  29. case 'logout':
  30. session_destroy();
  31. header('Location:index.php');
  32. break;
  33. default:
  34. exit('非法请求');
  35. }
  36. function loginCheck($name, $pwd)
  37. {
  38. global $pdo;
  39. $sql = "SELECT `username`,`password` FROM `user` WHERE `username` = ? AND `password` = ? ";
  40. $stmt = $pdo->prepare($sql);
  41. $res = $stmt->execute([$name, md5($pwd)]);
  42. if ($res) {
  43. $res = $stmt->fetch(PDO::FETCH_ASSOC);
  44. if ($res) {
  45. $_SESSION['username'] = $res['username'];
  46. return true;
  47. } else {
  48. return false;
  49. }
  50. }
  51. }
  52. function insertData($name, $pwd, $gender, $created_at)
  53. {
  54. global $pdo;
  55. $flag = false;
  56. $sql = "INSERT INTO `user` SET `username` =?,`password`=?, `gender`=?,`created_at`=? ";
  57. $stmt = $pdo->prepare($sql);
  58. $stmt->execute([$name, $pwd, $gender, $created_at]);
  59. if ($stmt->rowCount() == 1) {
  60. $flag = true;
  61. }
  62. return $flag;
  63. }
  64. ?>