博客列表 >将请求分发器的注册与退出登录完善

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

中三
中三原创
2022年01月26日 18:14:47318浏览
  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. ?>
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议