Blogger Information
Blog 30
fans 0
comment 1
visits 22024
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
0114PHP会话控制实战cookie&&session
Admin
Original
471 people have browsed it

PHP会话控制实战

首先我们先写案例一个首页(就随便写了一个导航)一个登陆页面一个注册页面



然后我们先整理一下思路

  • 首先我们要写好表单,method,action什么的要写好。
  • 其次我们要写一个验证脚本用来验证账号密码是否正确,登陆,退出这三个功能。
  • 然后就是判断一下是否已经登陆,其实就这么三块。

    Login部分(不是重点)

    1. <?php
    2. if (filter_has_var(INPUT_COOKIE, 'user')) {
    3. exit('<script>alert("你已经登入了不要重复登陆噢");location.href="index.php"</script>');
    4. }
    5. ?>
    6. <!DOCTYPE html>
    7. <html lang="en">
    8. <head>
    9. <meta charset="UTF-8">
    10. <title>后台登陆</title>
    11. <link rel="stylesheet" href="../css/bootstrap.css">
    12. <link rel="stylesheet" type="text/css" href="../css/login.css">
    13. </head>
    14. <body>
    15. <div class="login">
    16. <div class="main">
    17. <div class="logo">
    18. <strong id="logintitle">用户登陆</strong>
    19. </div>
    20. <form action="handle.php?action=login" method="post">
    21. <input type="text" name="username" placeholder="输入用户名" name="username">
    22. <hr class="hr11">
    23. <input type="password" name="password" placeholder="输入密码" name="password">
    24. <hr class="hr11">
    25. <button type="submit" class="btn btn-primary btn-lg btn-block">登陆</button>
    26. <button type="button" class="btn btn-lg btn-block btn-info" onclick="hreftz()">注册</button>
    27. </form>
    28. </div>
    29. </div>
    30. </body>
    31. <script>
    32. function hreftz() {
    33. window.location.href = "register.php";
    34. }
    35. </script>
    36. </html>

    验证脚本

    1. <?php
    2. $users = [
    3. [
    4. 'id' => 1,
    5. 'name' => 'admin',
    6. 'email' => 'admin@php.cn',
    7. 'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
    8. ],
    9. [
    10. 'id' => 2,
    11. 'name' => 'peter',
    12. 'email' => 'peter@php.cn',
    13. 'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
    14. ],
    15. ];
    16. //获取来源链接
    17. $urlcheck = filter_input(INPUT_SERVER, 'HTTP_REFERER');
    18. $saferules = [
    19. 'login.php',
    20. 'index.php',
    21. 'register.php'
    22. ];
    23. $url = basename($urlcheck);
    24. if (!in_array($url, $saferules)) {
    25. exit('非法来源,拒绝访问!');
    26. }
    27. $action = filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
    28. switch ($action) {
    29. //登陆模块
    30. case 'login':
    31. //检查数据来源是否合法
    32. if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') {
    33. //获取邮箱
    34. $username = filter_var(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING), FILTER_VALIDATE_EMAIL);
    35. //获取密码
    36. $password = sha1(filter_input(INPUT_POST, 'password'));
    37. //接下来与数组进行验证
    38. $res = array_filter($users, function ($users) use ($username, $password) {
    39. return $username === $users['email'] && $password === $users['password'];
    40. });
    41. //如果$res的值是true那就是账号密码验证通过了
    42. if (count($res) === 1) {
    43. setcookie('user', serialize(array_pop($res)));
    44. exit('<script>alert("登陆成功");location.href="index.php"</script>');
    45. } else {
    46. exit('<script>alert("账号或者密码不正确");location.href="index.php"</script>');
    47. }
    48. } else {
    49. exit('提交数据非法');
    50. }
    51. break;
    52. case 'register':
    53. //通过过滤器获取用户名
    54. $name =filter_var(filter_input(INPUT_POST,'name'),FILTER_SANITIZE_SPECIAL_CHARS);
    55. //获取邮箱
    56. $email = filter_var(filter_input(INPUT_POST,'email',FILTER_SANITIZE_STRING),FILTER_VALIDATE_EMAIL);
    57. $password = sha1(filter_input(INPUT_POST,'p1'));
    58. $password1 = sha1(filter_input(INPUT_POST,'p2'));
    59. if ($password !== $password1) {
    60. exit('<script>alert("第一次密码输入与第二次密码输入不同");location.href="register.php"</script>');
    61. }
    62. $id=3;
    63. //接下来判断OK了之后应该写入数据库
    64. $data = compact('id','name','email','password');
    65. //方法一:如下; 方法二:直接 $users[]=$data;
    66. if(array_push($users,$data)){
    67. exit('<script>alert("注册成功");location.href="login.php"</script>');
    68. }
    69. break;
    70. case 'logout':
    71. if (filter_input(INPUT_COOKIE, 'user')) {
    72. setcookie('user', null, time() - 3600);
    73. exit('<script>alert("退出成功");location.href="index.php"</script>');
    74. }
    75. break;
    76. }
    验证脚本这一块,用的最多的就是那啥过滤器,filter_input,filter_var照着手册边查边打,自然而然就记住了,并且养成写注释的习惯
    一般来说cookie的过期时间可以这样子设置time()-3600

    Index.php页面就写个判断登陆获取一下用户名

    1. <?php
    2. //判断是否已经登陆
    3. if (filter_has_var(INPUT_COOKIE, 'user')) {
    4. $user = unserialize(filter_input(INPUT_COOKIE, 'user'));
    5. }
    6. ?>
    7. <!DOCTYPE html>
    8. <html lang="en">
    9. <head>
    10. <meta charset="UTF-8">
    11. <meta name="viewport" content="width=device-width, initial-scale=1.0">
    12. <meta http-equiv="X-UA-Compatible" content="ie=edge">
    13. <title>Document</title>
    14. <style>
    15. * {
    16. margin: 0;
    17. padding: 0;
    18. }
    19. nav {
    20. height: 35px;
    21. width: 100%;
    22. padding: 0 20px;
    23. box-sizing: border-box;
    24. background: black;
    25. display: flex;
    26. justify-content: space-between;
    27. }
    28. nav>a {
    29. line-height: 35px;
    30. text-decoration: none;
    31. color: white;
    32. }
    33. </style>
    34. </head>
    35. <body>
    36. <nav>
    37. <a href="">LOGO</a>
    38. <?php if (isset($user)) : ?>
    39. <a href="" id="logout">
    40. <span><?php echo $user['name'] ?></span>
    41. 退出
    42. </a>
    43. <?php else : ?>
    44. <a href="login.php">登陆</a>
    45. <?php endif ?>
    46. </nav>
    47. <script>
    48. // 为退出按钮创建事件监听器
    49. if (document.querySelector('#logout') !== null) {
    50. document.querySelector('#logout').addEventListener('click', function(event) {
    51. if (confirm('是否退出')) {
    52. // 禁用默认行为, 其实就是禁用原<a>标签的点击跳转行为,使用事件中的自定义方法处理
    53. event.preventDefault();
    54. // 跳转到退出事件处理器
    55. window.location.assign('handle.php?action=logout');
    56. }
    57. });
    58. }
    59. </script>
    60. </body>
    61. </html>
    顺便提一句这里的querySelectorgetElementBy是有区别的querySelector是根据CSS选择器来的

    register.php

    1. <!DOCTYPE html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>后台登陆</title>
    6. <link rel="stylesheet" href="../css/bootstrap.css">
    7. <link rel="stylesheet" type="text/css" href="../css/login.css">
    8. </head>
    9. <body>
    10. <div class="login">
    11. <div class="main">
    12. <div class="logo">
    13. <strong id="logintitle">用户注册</strong>
    14. </div>
    15. <form action="handle.php?action=register" onsubmit="return compare()" method="post">
    16. <input type="text" placeholder="用户名" name="name">
    17. <hr class="hr11">
    18. <input type="text" placeholder="邮箱" name="email">
    19. <hr class="hr11">
    20. <input type="password" placeholder="密码" id="p1" name="password">
    21. <hr class="hr11">
    22. <input type="password" placeholder="重复密码" id="p2" name="password">
    23. <hr class="hr11">
    24. <button type="submit" class="btn btn-lg btn-block btn-info">注册</button>
    25. <span id="tips" style="color: red"></span>
    26. </form>
    27. </div>
    28. </div>
    29. <script>
    30. // 验证二次密码是否相等?
    31. function compare() {
    32. if (document.forms[0].p1.value.trim() !== document.forms[0].p2.value.trim()) {
    33. document.querySelector('#tips').innerText = '二次密码不相等';
    34. return false;
    35. }
    36. }
    37. </script>
    38. </body>
    39. </html>

    Session

    Session最重要的其实是开启sessionsession_start什么页面要用什么页面就要开启

    验证脚本

    1. <?php
    2. session_start();
    3. $users = [
    4. [
    5. 'id' => 1,
    6. 'name' => 'admin',
    7. 'email' => 'admin@php.cn',
    8. 'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
    9. ],
    10. [
    11. 'id' => 2,
    12. 'name' => 'peter',
    13. 'email' => 'peter@php.cn',
    14. 'password' => '7c4a8d09ca3762af61e59520943dc26494f8941b',
    15. ],
    16. ];
    17. //获取来源链接
    18. $urlcheck = filter_input(INPUT_SERVER, 'HTTP_REFERER');
    19. $saferules = [
    20. 'login.php',
    21. 'index.php',
    22. 'register.php'
    23. ];
    24. $url = basename($urlcheck);
    25. if (!in_array($url, $saferules)) {
    26. exit('非法来源,拒绝访问!');
    27. }
    28. $action = filter_input(INPUT_GET, 'action', FILTER_SANITIZE_STRING);
    29. switch ($action) {
    30. //登陆模块
    31. case 'login':
    32. //检查数据来源是否合法
    33. if (filter_input(INPUT_SERVER, 'REQUEST_METHOD') === 'POST') {
    34. //获取邮箱
    35. $username = filter_var(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING), FILTER_VALIDATE_EMAIL);
    36. //获取密码
    37. $password = sha1(filter_input(INPUT_POST, 'password'));
    38. //接下来与数组进行验证
    39. $res = array_filter($users, function ($users) use ($username, $password) {
    40. return $username === $users['email'] && $password === $users['password'];
    41. });
    42. //如果$res的值是true那就是账号密码验证通过了
    43. if (count($res) === 1) {
    44. $_SESSION['user'] = serialize(array_pop($res));
    45. exit('<script>alert("登陆成功");location.href="index.php"</script>');
    46. } else {
    47. exit('<script>alert("账号或者密码不正确");location.href="index.php"</script>');
    48. }
    49. } else {
    50. exit('提交数据非法');
    51. }
    52. break;
    53. case 'register':
    54. //通过过滤器获取用户名
    55. $name = filter_var(filter_input(INPUT_POST, 'name'), FILTER_SANITIZE_SPECIAL_CHARS);
    56. //获取邮箱
    57. $email = filter_var(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING), FILTER_VALIDATE_EMAIL);
    58. $password = sha1(filter_input(INPUT_POST, 'p1'));
    59. $password1 = sha1(filter_input(INPUT_POST, 'p2'));
    60. if ($password !== $password1) {
    61. exit('<script>alert("第一次密码输入与第二次密码输入不同");location.href="register.php"</script>');
    62. }
    63. $id = 3;
    64. //接下来判断OK了之后应该写入数据库
    65. $data = compact('id', 'name', 'email', 'password');
    66. //方法一:如下; 方法二:直接 $users[]=$data;
    67. if (array_push($users, $data)) {
    68. exit('<script>alert("注册成功");location.href="login.php"</script>');
    69. }
    70. break;
    71. case 'logout':
    72. if (isset($_SESSION['user'])) {
    73. session_destroy();
    74. exit('<script>alert("退出成功");location.href="index.php"</script>');
    75. }
    76. break;
    77. }

    Index.php核心代码

    1. session_start();
    2. //判断是否已经登陆
    3. if (isset($_SESSION['user'])) {
    4. $user = unserialize($_SESSION['user']);
    5. }

    Login.php

    1. if (isset($_SESSION['user'])) {
    2. exit('<script>alert("你已经登入了不要重复登陆噢");location.href="index.php"</script>');
    3. }
    因为PHP没有关于SESSION的过滤器所以我们直接用isset就完事了

    接下来是SESSION和COOKIE的理解图

Correction status:Uncorrected

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