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

0822用户登录、注册、退出

小言
小言原创
2022年08月24日 14:31:07350浏览


用户登录、注册、退出,我们主要是为了演示 cookiesession 的使用方法。

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