博客列表 >用户登录、注册、退出

用户登录、注册、退出

P粉191340380
P粉191340380原创
2022年08月30日 23:54:41328浏览

handle.php

  1. namespace _0822;
  2. use PDO;
  3. session_start();
  4. $db = new PDO('mysql:dbname=phpedu','root','root');
  5. $stmt = $db->prepare('SELECT * FROM `user`;');
  6. if (stmt->execute()){
  7. $users = $stmt->fetchAll(PDO::FECTH_ASSOC);
  8. }else{
  9. printf_r($stmt->errorInfo());
  10. }
  11. // 获取用户操作数据
  12. $action = strtolower($_GET['action']);
  13. switch($action){
  14. //登录
  15. case 'login':
  16. if($_SERVER['REQUEST_METHOD']==='POST'){
  17. //获取登录用户的数据:邮箱和密码
  18. $email = $_POST['email'];
  19. $password = sha1($_POST['password']);
  20. $result = array_filter($users,function($user) use($email,$password){
  21. return $user['email'] === $email && $user['password'] === $password;
  22. });
  23. if(count($result)===1){
  24. // 登录成功,写入session
  25. $_SESSION['user'] = serialize(array_pop($result));
  26. exit('<script>alert("验证通过"),location.href="index.php"</script>');
  27. }
  28. print_r($result);
  29. } else{
  30. // echo '请求类型错误'; die;
  31. exit('请求类型错误');
  32. }
  33. // 退出
  34. case 'logout': if(isset($_SESSION['user'])){
  35. session_destroy();
  36. exit('<script>alert("退出成功"),location.href="index.php"</script>');
  37. }
  38. // 注册
  39. case 'register':
  40. // 1. 获取登录用户的数据
  41. $email = $_POST['email'];
  42. $name = $_POST['name'];
  43. $password = sha1($_POST['p2']);
  44. $register_time = time();
  45. // 2. SQL
  46. $sql = <<< SQL
  47. INSERT `user`
  48. SET `name`= ?,
  49. `email`= ?,
  50. `password`= ?,
  51. `register_time`= ?;
  52. SQL;
  53. $stmt = $db->prepare($sql);
  54. $data = [$name,$email,$password,$register_time];
  55. if ($stmt->execute($data)) {
  56. if($stmt->rowCount() > 0){
  57. // 注册成功之后,让用户自动登录
  58. $sql = 'SELECT * FROM `user` WHERE `id`= ' . $db->lastInsertId();
  59. $stmt = $db->prepare($sql);
  60. $stmt->execute();
  61. $newUser = $stmt->fetch(PDO::FETCH_ASSOC);
  62. $_SESSION['user'] = serialize($newUser);
  63. exit('<script>alert("注册成功"),location.href="index.php"</script>');
  64. } else{
  65. exit('<script>alert("注册失败"),location.href="register.php"</script>');
  66. }
  67. } else {
  68. print_r($stmt->errorInfo());
  69. }
  70. // no break
  71. default:
  72. exit('参数非法或未定义操作');
  73. })
  74. }
  75. }
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议