ASCII码 ASCII码

PDO登录实战完善请求分发器小结

发布于:2022-04-16 12:19:13  栏目:技术文档

PDO登录实战

1. 文件结构

2. 首页

  1. <!DOCTYPE html>
  2. <?php session_start() ?>
  3. <!DOCTYPE html>
  4. <html lang="en">
  5. <head>
  6. <meta charset="UTF-8">
  7. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  8. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  9. <title>首页</title>
  10. <style>
  11. html {
  12. background: url(https://t7.baidu.com/it/u=2961459243,2146986594&fm=193&f=GIF) no-repeat;
  13. background-size: 100%;
  14. }
  15. header {
  16. max-width: 996px;
  17. margin: auto;
  18. padding: 0.5em 0.5em;
  19. background-color: #4395ff;
  20. display: flex;
  21. place-content: space-between;
  22. }
  23. a {
  24. margin-right: 1em;
  25. color: #eee;
  26. text-decoration: none;
  27. }
  28. a:hover {
  29. color: yellow;
  30. }
  31. </style>
  32. </head>
  33. <body>
  34. <header>
  35. <a href="">首页</a>
  36. <nav>
  37. <?php
  38. if (!isset($_SESSION['username']) || empty($_SESSION['username'])) {
  39. echo "
  40. <a href='login.php'>登录</a>
  41. <a href='register.php'>注册</a>
  42. ";
  43. } else {
  44. echo "
  45. <a href=''>{$_SESSION['username']}</a>
  46. <a href='request_controller.php?type=logout'>退出</a>
  47. ";
  48. }
  49. ?>
  50. </nav>
  51. </header>
  52. </body>
  53. </html>

3. 登录

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>PDO登录实战</title>
  8. <!-- 引入md5加密文件 -->
  9. <script src="../public/md5.js"></script>
  10. <style>
  11. .form {
  12. width: 220px;
  13. height: 100px;
  14. margin: 10% auto;
  15. display: grid;
  16. }
  17. input {
  18. margin: 10px;
  19. text-align: center;
  20. }
  21. .btn {
  22. cursor: pointer;
  23. }
  24. h4 {
  25. text-align: center;
  26. }
  27. </style>
  28. </head>
  29. <body>
  30. <form class="form" id="form">
  31. <h4>PDO登录实战</h4>
  32. <input
  33. type="text"
  34. name="username"
  35. id="username"
  36. placeholder="请输入用户名"
  37. />
  38. <input
  39. type="password"
  40. name="password"
  41. id="password"
  42. placeholder="请输入密码"
  43. />
  44. <input type="button" value="登 录" class="btn" onclick="login()" />
  45. </form>
  46. <script>
  47. async function login() {
  48. // 取得输入的用户名和密码
  49. let username = document.forms.form.username.value;
  50. let password = hex_md5(document.forms.form.password.value);
  51. // 请求分发文件链接
  52. url = "Request_Controller.php?type=login";
  53. // 定义常量存贮异步请求响应
  54. const response = await fetch(url, {
  55. method: "POST",
  56. headers: {
  57. "Content-type": "application/x-www-form-urlencoded;charset=utf-8",
  58. },
  59. body: `username=${username}&password=${password}`,
  60. });
  61. response.json().then((res_json) => {
  62. if (res_json.status) {
  63. window.location.href = "index.php";
  64. } else {
  65. alert(res_json.msg);
  66. }
  67. });
  68. }
  69. </script>
  70. </body>
  71. </html>

4. 注册

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>用户注册</title>
  8. <script src="../public/md5.js"></script>
  9. <style>
  10. .form {
  11. width: 220px;
  12. height: 100px;
  13. margin: 10% auto;
  14. display: grid;
  15. }
  16. input,
  17. p {
  18. margin: 10px;
  19. padding: 0.2em;
  20. text-align: center;
  21. }
  22. .btn:hover,
  23. label:hover {
  24. cursor: pointer;
  25. }
  26. .btn:disabled {
  27. cursor: not-allowed;
  28. }
  29. h3 {
  30. text-align: center;
  31. }
  32. label {
  33. margin: 0 1em;
  34. }
  35. </style>
  36. </head>
  37. <body>
  38. <form class="form" id="form">
  39. <h3>用户注册</h3>
  40. <input type="text" name="username" id="username" placeholder="用户名,必须中文" onblur="check_user(this)" value="" />
  41. <input type="password" name="password" id="password" placeholder="密码,必须大于或等于6位" onblur="check_password(this)" />
  42. <input type="password" name="check_pwd" id="check_pwd" placeholder="确认密码" onblur="check_check_pwd(this)" />
  43. <p>
  44. <label for="man">男<input type="radio" name="gender" id="man" value="1" checked></label>
  45. <label for="women">女<input type="radio" name="gender" id="women" value="0"></label>
  46. </p>
  47. <input type="button" value="提 交" class="btn" onclick="register()" disabled />
  48. </form>
  49. <script>
  50. /*
  51. * 验证表单,只写了简单的验证功能原代码,实际开发多用插件,自带验证功能
  52. */
  53. // 变量记录验证通过情况
  54. let check_status = [0, 0, 0]
  55. btn_status(check_status)
  56. document.querySelector("#username").value = ""
  57. // 验证用户名,只能是中文
  58. async function check_user(ev) {
  59. const test = /^[\u4E00-\u9FA5]+$/
  60. if (!test.test(ev.value) || ev.value.length == 0) {
  61. alert("用户名不能为空,并且只能是中文!")
  62. ev.value = ev.value.replace(/[^\u4e00-\u9fa5]/g, '')
  63. check_status[0] = 0
  64. } else {
  65. // 检查用户名是否存在
  66. url = "Request_Controller.php?type=duplicate_name";
  67. // 定义常量存贮异步请求响应
  68. const response = await fetch(url, {
  69. method: "POST",
  70. headers: {
  71. "Content-type": "application/x-www-form-urlencoded;charset=utf-8",
  72. },
  73. body: `username=${ev.value}`,
  74. });
  75. response.json().then((res_json) => {
  76. if (res_json.status) {
  77. alert(res_json.msg)
  78. check_status[0] = 0
  79. btn_status(check_status)
  80. } else {
  81. alert(res_json.msg)
  82. check_status[0] = 1
  83. btn_status(check_status)
  84. }
  85. })
  86. }
  87. }
  88. // 验证密码,必须大于6位
  89. function check_password(ev) {
  90. if (ev.value.length < 6) {
  91. alert("密码必须大于等于6位!")
  92. check_status[1] = 0
  93. } else {
  94. check_status[1] = 1
  95. }
  96. btn_status(check_status)
  97. }
  98. // 再次验证密码是否一致
  99. function check_check_pwd(ev) {
  100. if (ev.value != document.querySelector("#password").value) {
  101. alert("两次输入的密码不一致!")
  102. check_status[2] = 0
  103. } else {
  104. check_status[2] = 1
  105. }
  106. btn_status(check_status)
  107. }
  108. // 设置提交按钮是否可用
  109. function btn_status(status) {
  110. if (status.toString() === [1, 1, 1].toString()) {
  111. document.querySelector(".btn").removeAttribute("disabled")
  112. } else {
  113. document.querySelector(".btn").disabled = "true"
  114. }
  115. }
  116. async function register() {
  117. // 取得输入的用户名和密码
  118. let username = document.forms.form.username.value
  119. let password = hex_md5(document.forms.form.password.value)
  120. let gender = document.forms.form.gender.value
  121. // 请求链接
  122. url = "Request_Controller.php?type=register"
  123. // 定义常量存贮异步请求响应
  124. const response = await fetch(url, {
  125. method: "POST",
  126. headers: {
  127. "Content-type": "application/x-www-form-urlencoded;charset=utf-8",
  128. },
  129. body: `username=${username}&password=${password}&gender=${gender}`,
  130. });
  131. response.json().then((res_json) => {
  132. if (res_json.status) {
  133. alert("注册成功,请登录。")
  134. window.location.href = "login.php"
  135. } else {
  136. alert(res_json.msg)
  137. }
  138. })
  139. }
  140. </script>
  141. </body>
  142. </html>

5. 请求分发器

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>用户注册</title>
  8. <script src="../public/md5.js"></script>
  9. <style>
  10. .form {
  11. width: 220px;
  12. height: 100px;
  13. margin: 10% auto;
  14. display: grid;
  15. }
  16. input,
  17. p {
  18. margin: 10px;
  19. padding: 0.2em;
  20. text-align: center;
  21. }
  22. .btn:hover,
  23. label:hover {
  24. cursor: pointer;
  25. }
  26. .btn:disabled {
  27. cursor: not-allowed;
  28. }
  29. h3 {
  30. text-align: center;
  31. }
  32. label {
  33. margin: 0 1em;
  34. }
  35. </style>
  36. </head>
  37. <body>
  38. <form class="form" id="form">
  39. <h3>用户注册</h3>
  40. <input type="text" name="username" id="username" placeholder="用户名,必须中文" onblur="check_user(this)" value="" />
  41. <input type="password" name="password" id="password" placeholder="密码,必须大于或等于6位" onblur="check_password(this)" />
  42. <input type="password" name="check_pwd" id="check_pwd" placeholder="确认密码" onblur="check_check_pwd(this)" />
  43. <p>
  44. <label for="man">男<input type="radio" name="gender" id="man" value="1" checked></label>
  45. <label for="women">女<input type="radio" name="gender" id="women" value="0"></label>
  46. </p>
  47. <input type="button" value="提 交" class="btn" onclick="register()" disabled />
  48. </form>
  49. <script>
  50. /*
  51. * 验证表单,只写了简单的验证功能原代码,实际开发多用插件,自带验证功能
  52. */
  53. // 变量记录验证通过情况
  54. let check_status = [0, 0, 0]
  55. btn_status(check_status)
  56. document.querySelector("#username").value = ""
  57. // 验证用户名,只能是中文
  58. async function check_user(ev) {
  59. const test = /^[\u4E00-\u9FA5]+$/
  60. if (!test.test(ev.value) || ev.value.length == 0) {
  61. alert("用户名不能为空,并且只能是中文!")
  62. ev.value = ev.value.replace(/[^\u4e00-\u9fa5]/g, '')
  63. check_status[0] = 0
  64. } else {
  65. // 检查用户名是否存在
  66. url = "Request_Controller.php?type=duplicate_name";
  67. // 定义常量存贮异步请求响应
  68. const response = await fetch(url, {
  69. method: "POST",
  70. headers: {
  71. "Content-type": "application/x-www-form-urlencoded;charset=utf-8",
  72. },
  73. body: `username=${ev.value}`,
  74. });
  75. response.json().then((res_json) => {
  76. if (res_json.status) {
  77. alert(res_json.msg)
  78. check_status[0] = 0
  79. btn_status(check_status)
  80. } else {
  81. alert(res_json.msg)
  82. check_status[0] = 1
  83. btn_status(check_status)
  84. }
  85. })
  86. }
  87. }
  88. // 验证密码,必须大于6位
  89. function check_password(ev) {
  90. if (ev.value.length < 6) {
  91. alert("密码必须大于等于6位!")
  92. check_status[1] = 0
  93. } else {
  94. check_status[1] = 1
  95. }
  96. btn_status(check_status)
  97. }
  98. // 再次验证密码是否一致
  99. function check_check_pwd(ev) {
  100. if (ev.value != document.querySelector("#password").value) {
  101. alert("两次输入的密码不一致!")
  102. check_status[2] = 0
  103. } else {
  104. check_status[2] = 1
  105. }
  106. btn_status(check_status)
  107. }
  108. // 设置提交按钮是否可用
  109. function btn_status(status) {
  110. if (status.toString() === [1, 1, 1].toString()) {
  111. document.querySelector(".btn").removeAttribute("disabled")
  112. } else {
  113. document.querySelector(".btn").disabled = "true"
  114. }
  115. }
  116. async function register() {
  117. // 取得输入的用户名和密码
  118. let username = document.forms.form.username.value
  119. let password = hex_md5(document.forms.form.password.value)
  120. let gender = document.forms.form.gender.value
  121. // 请求链接
  122. url = "Request_Controller.php?type=register"
  123. // 定义常量存贮异步请求响应
  124. const response = await fetch(url, {
  125. method: "POST",
  126. headers: {
  127. "Content-type": "application/x-www-form-urlencoded;charset=utf-8",
  128. },
  129. body: `username=${username}&password=${password}&gender=${gender}`,
  130. });
  131. response.json().then((res_json) => {
  132. if (res_json.status) {
  133. alert("注册成功,请登录。")
  134. window.location.href = "login.php"
  135. } else {
  136. alert(res_json.msg)
  137. }
  138. })
  139. }
  140. </script>
  141. </body>
  142. </html>

6. 连接数据库

  1. <?php
  2. /*
  3. * PDO连接数据库文件
  4. * 参数:$DB_type 数据库类型名,默认为mysql
  5. * 参数:$DB_host 数据库服务器名,默认为localhost
  6. * 参数:$DB_port 数据库数据库服务器端口,默认为'3308'
  7. * 参数:$DB_username 数据库服务器用户名,默认为'root'
  8. * 参数:$DB_password 数据库服务器密码,默认为''
  9. * 参数:$DB_dbname 数据库名,默认为 'php'
  10. * 参数:$DB_charset 字符集,默认为 ''utf8mb4'
  11. * 以上变量在引入文件处可设置值
  12. * 连接错误请注意检查是否有与参数重名的变量
  13. */
  14. $DB_type = $DB_type ?? 'mysql';
  15. $DB_host = $DB_host ?? 'localhost';
  16. $DB_port = $DB_port ?? '3308';
  17. $DB_dbname = $DB_dbname ?? 'php';
  18. $DB_charset = $DB_charset ?? 'utf8mb4';
  19. $DB_username = $DB_username ?? 'root';
  20. $DB_password = $DB_password ?? '';
  21. // 定义数据库连接字串
  22. $dsn = '%s:host=%s;port=%s;dbname=%s;charset=%s';
  23. $dsn = sprintf($dsn, $DB_type, $DB_host, $DB_port, $DB_dbname, $DB_charset);
  24. // 连接数据库
  25. try {
  26. $pdo = new PDO($dsn, $DB_username, $DB_password);
  27. } catch (PDOException $err) {
  28. // PDOException异常类,指定变量$err为异常类型变量
  29. die('连接错误:' . $err->getMessage());
  30. }

7. 数据处理模型

  1. <?php
  2. /*
  3. * 数据处理模型
  4. */
  5. // 连接数据库
  6. require_once 'conn.php';
  7. session_start();
  8. // 验证登录用户名密码
  9. function check_user($user, $pwd)
  10. {
  11. global $pdo; // 声明pdo为全局变量,才能在函数中调用
  12. $sql = 'SELECT `name` FROM `user` WHERE `name`=? AND `pass`=? ';
  13. $stmt = $pdo->prepare($sql);
  14. $stmt->execute([$user, $pwd]);
  15. $res = $stmt->fetchAll(PDO::FETCH_ASSOC);
  16. if ($res) {
  17. //验证通过记录用户名
  18. $_SESSION['username'] = $user;
  19. return true;
  20. } else {
  21. return false;
  22. }
  23. }
  24. // 注册插入用户数据
  25. function add_user($user, $pwd, $gender)
  26. {
  27. global $pdo;
  28. $sql = 'INSERT INTO `user` (`name`,`pass`,`gender`) VALUES (?,?,?)';
  29. $stmt = $pdo->prepare($sql);
  30. $stmt->execute([$user, $pwd, $gender]);
  31. $res = $stmt->rowCount();
  32. if ($res) {
  33. return true;
  34. } else {
  35. return false;
  36. }
  37. }
  38. // 注册时检查用户名是否已存在
  39. function check_duplicate_name($name)
  40. {
  41. global $pdo;
  42. $sql = 'SELECT 1 FROM `user` WHERE `name`=?';
  43. $stmt = $pdo->prepare($sql);
  44. $stmt->execute([$name]);
  45. if ($stmt->rowCount()) {
  46. return true;
  47. } else {
  48. return false;
  49. }
  50. }
  51. // 删除一条数据
  52. // $sql = 'DELETE FROM `user` WHERE `id`=?';
  53. // $stmt = $pdo->prepare($sql);
  54. // $stmt->execute([3]);
  55. // if ($stmt->rowCount() === 1) {
  56. // echo '删除成功<br>';
  57. // } else {
  58. // echo '删除失败<br>';
  59. // }
  60. // 更新一条数据
  61. // $sql = 'UPDATE `user` SET `pass`=? WHERE `id`=?';
  62. // $pass = md5('654321');
  63. // $id = 1;
  64. // $stmt = $pdo->prepare($sql);
  65. // $stmt->execute([$pass, $id]);
  66. // if ($stmt->rowCount() === 1) {
  67. // echo '更新密码成功<br>';
  68. // } else {
  69. // echo '更新密码失败<br>';
  70. // }

相关推荐
阅读 +