Blogger Information
Blog 119
fans 3
comment 1
visits 94683
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PHP会话控制实战cookie、session
赵大叔
Original
777 people have browsed it

COOKIE

1、数据保存在客户端浏览器上,如果浏览器关闭cookie,则无法使用
2、创建cookie:setcookie(名称,值,[过期时间])
3、使用cookie:$_COOKIE['名称']
4、删除cookie:为cookie设置一个已经过期的时间,如:setcookie(名称,值,time()-1)

演示代码

首页:

  1. <?php
  2. // 判断是否已经登录?
  3. if (isset($_COOKIE['user'])) $user = unserialize($_COOKIE['user']);
  4. ?>
  5. <!doctype html>
  6. <html lang="en">
  7. <head>
  8. <meta charset="UTF-8">
  9. <title>首页</title>
  10. <style>
  11. nav {
  12. height: 60px;
  13. background-color: black;
  14. padding: 0 20px;
  15. display: flex;
  16. justify-content: space-between;
  17. align-items: center;
  18. }
  19. nav a {
  20. color: white;
  21. text-decoration: none;
  22. }
  23. div {
  24. display: flex;
  25. align-items: center;
  26. }
  27. nav img {
  28. width: 40px;
  29. border-radius: 50%;
  30. margin-right: 10px;
  31. }
  32. </style>
  33. </head>
  34. <body>
  35. <nav>
  36. <a href="index.php">我的博客</a>
  37. <div>
  38. <?php if (isset($user)) : ?>
  39. <a href=""><img src="user.jpg" alt=""></a>
  40. <a href="" id="logout"><span style="color:red"><?php echo $user['name']?></span>&nbsp;&nbsp;退出</a>
  41. <?php else: ?>
  42. <a href="login.php">登录</a>
  43. <?php endif ?>
  44. </div>
  45. </nav>
  46. <script>
  47. // 为退出按钮创建事件监听器
  48. if (document.querySelector('#logout') !== null) {
  49. document.querySelector('#logout').addEventListener('click', function(event) {
  50. if (confirm('是否退出')) {
  51. // 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
  52. event.preventDefault();
  53. // 跳转到退出事件处理器
  54. window.location.assign('handle.php?action=logout');
  55. }
  56. });
  57. }
  58. </script>
  59. </body>
  60. </html>

登录:

  1. <?php
  2. // 判断是否已登录
  3. if (isset($_COOKIE['user']))
  4. exit('<script>alert("请不要重复登录");location.href="index.php";</script>');
  5. ?>
  6. <!doctype html>
  7. <html lang="en">
  8. <head>
  9. <meta charset="UTF-8">
  10. <title>登录</title>
  11. <style>
  12. body {
  13. display: flex;
  14. flex-direction: column;
  15. text-align: center;
  16. color: #555;
  17. font-weight: 300;
  18. }
  19. body h3 {
  20. font-weight: 300;
  21. font-size: 20px;
  22. margin-bottom: 10px;
  23. }
  24. body form {
  25. width: 260px;
  26. padding: 20px;
  27. box-sizing: border-box;
  28. background-color: lightcyan;
  29. margin: auto;
  30. border-radius: 5px;
  31. box-shadow: 0 0 5px #aaa;
  32. }
  33. body form > div {
  34. height: 36px;
  35. display: flex;
  36. justify-content: space-between;
  37. align-items: center;
  38. }
  39. body form div:last-of-type {
  40. display: flex;
  41. justify-content: center;
  42. }
  43. body form input {
  44. border: none;
  45. outline: none;
  46. padding-left: 5px;
  47. height: 20px;
  48. }
  49. body form input:hover {
  50. box-shadow: 0 0 5px #aaa;
  51. }
  52. body form button {
  53. flex:auto;
  54. height: 30px;
  55. background-color: green;
  56. color: white;
  57. border: none;
  58. outline: none;
  59. }
  60. body form button:hover {
  61. background-color: lightcoral;
  62. cursor: pointer;
  63. box-shadow: 0 0 5px #aaa;
  64. }
  65. body a {
  66. color: #888;
  67. text-decoration: none;
  68. margin-top: 15px;
  69. }
  70. body a:hover {
  71. color: lightcoral;
  72. }
  73. </style>
  74. </head>
  75. <body>
  76. <h3>用户登录</h3>
  77. <form action="handle.php?action=login" method="post">
  78. <div>
  79. <label for="email">邮箱:</label>
  80. <input type="email" name="email" id="email" placeholder="demo@email.com" required autofocus>
  81. </div>
  82. <div>
  83. <label for="password">密码:</label>
  84. <input type="password" name="password" id="password" placeholder="不少于6位" required>
  85. </div>
  86. <div>
  87. <button>提交</button>
  88. </div>
  89. </form>
  90. <a href="register.php">还没有帐号, 注册一个吧</a>
  91. </body>
  92. </html>

注册:

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>注册</title>
  6. <style>
  7. body {
  8. display: flex;
  9. flex-direction: column;
  10. text-align: center;
  11. color: #555;
  12. font-weight: 300;
  13. }
  14. body h3 {
  15. font-weight: 300;
  16. font-size: 20px;
  17. margin-bottom: 10px;
  18. }
  19. body form {
  20. width: 260px;
  21. padding: 20px;
  22. box-sizing: border-box;
  23. background-color: lightcyan;
  24. margin: auto;
  25. border-radius: 5px;
  26. box-shadow: 0 0 5px #aaa;
  27. }
  28. body form > div {
  29. height: 36px;
  30. display: flex;
  31. justify-content: space-between;
  32. align-items: center;
  33. }
  34. body form div:last-of-type {
  35. display: flex;
  36. justify-content: center;
  37. }
  38. body form input {
  39. border: none;
  40. outline: none;
  41. padding-left: 5px;
  42. height: 20px;
  43. }
  44. body form input:hover {
  45. box-shadow: 0 0 5px #aaa;
  46. }
  47. body form button {
  48. flex:auto;
  49. height: 30px;
  50. background-color: green;
  51. color: white;
  52. border: none;
  53. outline: none;
  54. }
  55. body form button:hover {
  56. background-color: lightcoral;
  57. cursor: pointer;
  58. box-shadow: 0 0 5px #aaa;
  59. }
  60. body a {
  61. color: #888;
  62. text-decoration: none;
  63. margin-top: 15px;
  64. }
  65. body a:hover {
  66. color: lightcoral;
  67. }
  68. </style>
  69. </head>
  70. <body>
  71. <h3>用户注册</h3>
  72. <form action="handle.php?action=register" method="post" onsubmit="return compare()">
  73. <div>
  74. <label for="name">呢称:</label>
  75. <input type="text" name="name" id="name" placeholder="不少于3个字符" required autofocus>
  76. </div>
  77. <div>
  78. <label for="email">邮箱:</label>
  79. <input type="email" name="email" id="email" placeholder="demo@email.com" required>
  80. </div>
  81. <div>
  82. <label for="p1">密码:</label>
  83. <input type="password" name="p1" id="p1" placeholder="不少于6位" required>
  84. </div>
  85. <div>
  86. <label for="p2">重复:</label>
  87. <input type="password" name="p2" id="p2" placeholder="必须与上面一致" required>
  88. </div>
  89. <div>
  90. <button>提交</button><span id="tips" style="color: red"></span>
  91. </div>
  92. </form>
  93. <a href="login.php">我有帐号,直接登录</a>
  94. <script>
  95. // 验证二次密码是否相等?
  96. function compare() {
  97. if (document.forms[0].p1.value.trim() !== document.forms[0].p2.value.trim()) {
  98. document.querySelector('#tips').innerText = '二次密码不相等';
  99. return false;
  100. }
  101. }
  102. </script>
  103. </body>
  104. </html>

控制器:

  1. <?php
  2. // 数据库查询用户资料
  3. $pdo = new PDO('mysql:host=localhost;dbname=phpedu', 'root', 'root');
  4. $stmt = $pdo->prepare('SELECT * FROM `users`');
  5. $stmt->execute();
  6. $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
  7. // print_r($users);die;
  8. // 1. 验证请求来源的合法性
  9. // 设置合法请求地址的白名单
  10. $allowUrls = ['index.php', 'login.php', 'register.php'];
  11. // 获取当前的请求入口地址
  12. //basename():获取当前请求脚本名称
  13. $currentUrl = basename(filter_input(INPUT_SERVER, 'HTTP_REFERER'));
  14. //in_array(),判断当前请求在不在白名单
  15. if(!in_array($currentUrl, $allowUrls)){
  16. echo '非法来源';
  17. }else{
  18. // echo '合法来源';
  19. }
  20. // 2.进行请求分发处理
  21. //获取当前请求
  22. // echo $_GET['action'];
  23. //过滤处理, strtolower():字符串转为小写
  24. $action = strtolower(filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING));
  25. //switch判断当前请求
  26. switch($action){
  27. //登录
  28. case 'login':
  29. //判断是否是POST请求?
  30. if(filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST'){
  31. //获取当前请求的值:+清理特殊字符
  32. $email = filter_var(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL), FILTER_SANITIZE_EMAIL);
  33. $password = sha1(filter_input(INPUT_POST, 'password'));
  34. // echo $email, $password .'<hr>';
  35. //array_filter从数组中获取满足条件的值
  36. $results = array_filter($users, function ($user)use($email, $password){
  37. return $email === $user['email'] && $password === $user['password'];
  38. });
  39. // print_r($results);die;
  40. if(count($results) === 1) {
  41. //判断满足条件的指令数量=1?设置cookie
  42. //array_pop()=$results[0]
  43. setcookie('user', serialize(array_pop($results)));
  44. //print_r(unserialize($_COOKIE['user']));
  45. exit('<script>alert("验证通过");location.href="index.php"</script>');
  46. }else{
  47. exit('<script>alert("邮箱或密码错误,或没有帐号");location.href="register.php"</script>');
  48. }
  49. }else{
  50. exit('非法请求。');
  51. }
  52. break;
  53. //退出
  54. case 'logout':
  55. if (isset($_COOKIE['user'])) {
  56. setcookie('user', null , time()-3600);
  57. exit('<script>alert("退出成功");location.assign("index.php")</script>');
  58. }
  59. break;
  60. //注册
  61. case 'register':
  62. $name = filter_var(filter_input(INPUT_POST, 'name'), FILTER_SANITIZE_SPECIAL_CHARS);
  63. $email = filter_var(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL), FILTER_SANITIZE_EMAIL);
  64. $password = sha1(filter_input(INPUT_POST, 'p1'));
  65. $register_time = time();
  66. // echo $name .$email .$password .$register_time;die;
  67. // 2. 将新用户插入到表中
  68. $sql = "INSERT `users` SET `name`='{$name}', `password`='{$password}', `email`='{$email}', `register_time`={$register_time}";
  69. $stmt = $pdo->prepare($sql);
  70. $stmt->execute();
  71. if ($stmt->rowCount() === 1) exit('<script>alert("注册成功");location.assign("login.php")</script>');
  72. else exit('<script>alert("注册失败");location.assign("login.php")</script>');
  73. break;
  74. //未定义操作
  75. default:
  76. exit('未定义操作');
  77. }

效果图:

首页:

登录:

注册:

SESSION

1、数据保存在服务器上
2、启动session:session_start()
3、创建session:$_SESSION['名称']=值
4、使用session:$_SESSION['名称']
5、删除单个session:unset($_SESSION['名称'])
6、删除所有的session:session_unset()
7、销毁session:session_destory()

演示代码

首页:

  1. <?php
  2. // 开启会话
  3. session_start();
  4. // 判断是否已经登录?
  5. if (isset($_SESSION['user'])) $user = unserialize($_SESSION['user']);
  6. ?>

登录:

  1. <?php
  2. // 开启会话
  3. session_start();
  4. // 判断是否已登录
  5. if (isset($_SESSION['user']))
  6. exit('<script>alert("请不要重复登录");location.href="index.php";</script>');
  7. ?>

控制器:

  1. <?php
  2. // 开启会话
  3. session_start();
  4. // ......
  5. if(count($results) === 1) {
  6. //判断满足条件的指令数量=1?设置cookie
  7. //array_pop()=$results[0]
  8. $_SESSION['user'] = serialize(array_pop($results));
  9. //print_r(unserialize($_COOKIE['user']));
  10. exit('<script>alert("验证通过");location.href="index.php"</script>');
  11. }else{
  12. exit('<script>alert("邮箱或密码错误,或没有帐号");location.href="register.php"</script>');
  13. }
  14. case 'logout':
  15. if (isset($_SESSION['user'])) {
  16. session_destroy();
  17. exit('<script>alert("退出成功");location.assign("index.php")</script>');
  18. }
  19. break;
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:是的, 整个业务逻辑才是重点, 到于将用户数据存储在哪, 完全由程序员决定 , 而且就几行代码
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