实例演绎pdo在用户登录环节是怎么防sql注入及实战预处理与会话跟踪

实例演绎pdo在用户登录环节是怎么防sql注入的?

  1. $sql = 'SELECT `username`,`password` FROM `user` WHERE `username`= ? AND `password`=? ; ';//占位符来构成预处理语句
  2. $stmt = $pdo->prepare( $sql );//准备要执行的预处理语句,并返回语句对象
  3. $stmt->execute( [$username, $password] );//执行预处理语句
  4. $res = $stmt->fetch();
  5. if ( $res )
  6. {
  7. //验证通过 存session
  8. $_SESSION['username'] = $res['username'];
  9. echo json_encode( array( 'status'=>1, 'msg'=>'登录成功...正在跳转' ), 320 );
  10. exit;
  11. }
  12. echo json_encode( array( 'status'=>0, 'msg'=>'用户名或密码错误' ), 320 );

写一个小实战,实现预处理与会话跟踪?

一个前端页面显示文件,一个后端处理文件

后端文件实现预处理与会话跟踪

  1. <?php
  2. session_start();
  3. require 'config.php';
  4. $username = !empty( $_POST['username'] ) && isset( $_POST['username'] ) ? $_POST['username']:null;
  5. $password = !empty( $_POST['password'] ) && isset( $_POST['password'] ) ? md5( $_POST['password'] ):null;
  6. $code = !empty( $_POST['code_value'] ) && isset( $_POST['code_value'] ) ? $_POST['code_value'] :null;
  7. //请求分发器 type 1登录验证 2 验证码验证 3退出登录
  8. $type = isset( $_REQUEST['type'] ) && !empty( $_REQUEST['type'] ) ? intval( $_REQUEST['type'] ):null;
  9. switch( $type )
  10. {
  11. case 1:
  12. //检测用户是否存在
  13. $sql = 'SELECT `username`,`password` FROM `user` WHERE `username`= ? AND `password`=? ; ';
  14. $stmt = $pdo->prepare( $sql );
  15. $stmt->execute( [$username, $password] );
  16. $res = $stmt->fetch();
  17. if ( $res )
  18. {
  19. //验证通过 存session
  20. $_SESSION['username'] = $res['username'];
  21. echo json_encode( array( 'status'=>1, 'msg'=>'登录成功...正在跳转' ), 320 );
  22. exit;
  23. }
  24. echo json_encode( array( 'status'=>0, 'msg'=>'用户名或密码错误' ), 320 );
  25. break;
  26. case 2:
  27. //将session中的验证码和用户提交的验证码进行核对, 当成功时提示验证码正确,并销毁之前的session值, 不成功则重新提交 strcasecmp
  28. if ( !empty( $code ) && strtolower( $_SESSION['code'] ) === strtolower( $code ) ) {
  29. $_SESSION['code'] = '';
  30. echo json_encode( ['status'=>1, 'msg'=>'验证码正确'], 320 );
  31. exit;
  32. }
  33. echo json_encode( ['status'=>0, 'msg'=>'验证码不正确'], 320 );
  34. break;
  35. // 退出登录
  36. case 3:
  37. // 清空session变量
  38. session_unset();
  39. // 删除session文件
  40. session_destroy();
  41. header( 'Location: /demo.php' );
  42. break;
  43. default:
  44. echo json_encode( ['status'=>520, 'msg'=>'非法参数访问'], 320 );
  45. break;
  46. }

前端页面

  1. <?session_start()?>
  2. <!DOCTYPE html>
  3. <html lang = 'en'>
  4. <head>
  5. <meta charset = 'utf-8' />
  6. <title>用户登录</title>
  7. <meta name = 'viewport' content = 'width=device-width, initial-scale=1.0' />
  8. <meta name = 'description' content = 'Premium Bootstrap 4 Landing Page Template' />
  9. <meta name = 'keywords' content = 'bootstrap 4, premium, marketing, multipurpose' />
  10. <meta content = 'Themesdesign' name = 'author' />
  11. <!-- css -->
  12. <link href = 'login/static/bootstrap.min.css' rel = 'stylesheet' type = 'text/css' />
  13. <!--Themify Icon -->
  14. <link href = 'login/static/style.css' rel = 'stylesheet' type = 'text/css' />
  15. </head>
  16. <body>
  17. <section class = 'bg-login d-flex align-items-center'>
  18. <div class = 'container'>
  19. <div class = 'row justify-content-center mt-4'>
  20. <div class = 'col-lg-4'>
  21. <nav>
  22. <?php if (!isset($_SESSION['username']) || empty($_SESSION['username'])): ?>
  23. <div class = 'bg-white p-4 rounded'>
  24. <div class = 'text-center'>
  25. <h4 class = 'fw-bold mb-3'>用户登录</h4>
  26. </div>
  27. <div class = 'row login-form'>
  28. <div class = 'col-lg-12 mt-2'>
  29. <input type="text" name="username" class = 'form-control' placeholder="用户名" autofocus>
  30. </div>
  31. <div class = 'col-lg-12 mt-2'>
  32. <input type="password" name="password" class = 'form-control' placeholder="请输入密码" >
  33. </div>
  34. <div class = 'col-lg-12 mt-2'>
  35. <input type = 'code' class = 'form-control' placeholder = '验证码' required = '' name="code" id="code" style = 'float: left; width:55%;'>
  36. <label class = 'form-check-label'>
  37. <img src = 'login/code.php' onclick="this.src='login/code.php?id='+ Math.random();" height = '40px' style="margin: auto 10px;vertical-align: bottom; cursor:pointer" alt = '点击刷新'>
  38. </label>
  39. <span id="error_msg"> </span>
  40. </div>
  41. <div class = 'col-lg-12 mt-2'>
  42. <div class = 'form-check'>
  43. <input class = 'form-check-input' style = 'color: red;' type = 'checkbox' value = '' id = 'flexCheckDefault'>
  44. <label class = 'form-check-label' for = 'flexCheckDefault'>
  45. 记住
  46. </label>
  47. </div>
  48. </div>
  49. <div class = 'col-lg-12 mt-3 mb-4'>
  50. <button type ="button" class = 'btn btn-primary w-100' name="btn">登录</button>
  51. </div>
  52. <div class = 'txet-center'>
  53. <p class = 'mb-0 mt-2 text-center'>
  54. <a href = 'password_forget.html' class = 'text-dark fw-bold'>忘记密码 ?</a>
  55. </p>
  56. </div>
  57. </div>
  58. </div>
  59. <div class = 'text-center mt-3'>
  60. <p><small class = 'text-white mr-2'>未注册用户 ?</small> <a href = 'reg.html'
  61. class = 'text-white fw-bold'>创建账号</a></p>
  62. </div>
  63. <?php else : ?>
  64. <div class = 'text-center'>
  65. <h4 class = 'fw-bold mb-3'>您以成功登录</h4>
  66. <a href="javascript:;"><?=$_SESSION['username']?></a>&nbsp;
  67. <a href="login/login.php?type=3">退出</a>
  68. </div>
  69. <?php endif ?>
  70. </nav>
  71. </div>
  72. </div>
  73. </div>
  74. </section>
  75. <!-- javascript -->
  76. <script type = 'text/javascript' src = "
  77. https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
  78. <script type="text/javascript">
  79. //登录
  80. $('button[name="btn"]').click(function(){
  81. var data = {};
  82. data.username =$.trim($('input[name="username"]').val()) ;
  83. data.password = $.trim($('input[name="password"]').val());
  84. data.type = 1;
  85. var code = $.trim($('input[name="code"]').val())
  86. if(data.username == '' || data.password == '' || code == '')
  87. {
  88. alert('必选项不能为空哦~');
  89. return;
  90. }
  91. $.post('login/login.php',data,function(res){
  92. if(res.status == 1)
  93. {
  94. alert(res.msg);
  95. //用户验证通过 跳转首页
  96. setTimeout(()=>location.href = 'demo.php',500);
  97. }else{
  98. alert(res.msg);
  99. }
  100. },"json")
  101. })
  102. //使用ajax异步验证 验证码
  103. $('input[name="code"]').keyup(function(){
  104. var data={};
  105. data.code_value = $.trim($(this).val());
  106. data.type = 2;
  107. if(data.code_value == '')
  108. {
  109. $("#error_msg").html("<span style='color:green'>验证码不能为空</span>")
  110. return;
  111. }
  112. $.post('login/login.php',data,function(res){
  113. if(res.status == 1)
  114. {
  115. $("#error_msg").html("<span style='color:green'>验证码正确</span>")
  116. }else{
  117. $("#error_msg").html("<span style='color:red'>验证码错误</span>")
  118. }
  119. },"json")
  120. })
  121. </script>
  122. </body>
  123. </html>