博客列表 >动态分页制作及composer自动加载及第三方验证码使用

动态分页制作及composer自动加载及第三方验证码使用

缘亦
缘亦原创
2021年08月26日 16:32:47682浏览

composer类的自动加载机制

页面文件引用:
require 'vendor/lotoload.php';
在composer.json添加autoload字段,共有3三形式,推荐使用第3种方式:psr-4规范.添加完后要在终端中执行 composer dump-autoload这样做的自动加载才会生效

1.在composer.json添加autoload字段files

  1. "autoload":{
  2. "files": [
  3. "add/controller/Login.php",
  4. "add/controller/User.php"
  5. ]
  6. }

2.在composer.json添加autoload字段classmap,

  1. "autoload":{
  2. "classmap": [
  3. "add/controller/"
  4. ]
  5. }

3.psr-4规范,推荐使用

类的命名空间与类文件所在目录进行绑定,并且类文件名称与类名称保持一致,使用psr-4命名空间最后,必须以”\”空间分隔符结束,这样以来在绑定的目录中添加新类时,不必执行 composer dump-autoload操作就能生效

  1. "autoload":{
  2. "psr-4": {
  3. "app\\controller\\":"app/controller",
  4. "extend\\lib\\":"extend/lib"
  5. }
  6. }

实战:

使用composer安装三方验证码库完善登录页面,登录后转到用户列表页面,在这个页面做一个动态分页

除了composer相关的文件及第三方验证码库文件比较多就不贴出来了,贴出来所写的几个文件

  • login.php //登录界面
  • user.php //用户列表界面
  • dataBase.php //核心文件
  • session.php //验证码页面

先来看个实际演示

login.php登录界面

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

user.php //用户列表界面

  1. <?session_start()?>
  2. <? require 'dataBase.php' ?>
  3. <!DOCTYPE HTML>
  4. <html>
  5. <!DOCTYPE html>
  6. <html lang="en">
  7. <head>
  8. <meta charset="UTF-8">
  9. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  10. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  11. <title>用户修改</title>
  12. <style type="text/css">
  13. /*节省空间CSS给压缩了*/
  14. body,td,th{font-size:12px;font-family:"微软雅黑";}img{border:0;}ul,li{margin:0;padding:0;list-style:none;}ul.table1{height:30px;border-bottom:1px solid #fff;clear:both;}ul.table1 li{background:#61c0bf;float:left;border-right:1px #fff solid;line-height:30px;text-align:center;font-weight:bold;color:#fff;}ul.table2{height:30px;border-bottom:1px solid #fff;clear:both;}ul.table2 li{background:#bbded6;float:left;border-right:1px #fff solid;line-height:30px;text-align:center;}.name1{width:50px;}.name2{width:150px;}.name3{width:150px;}.name4{width:200px;}.name5{width:100px;text-align:left;}ul.pagination{display:inline-block;padding:0;margin:5px 0;}ul.pagination li{display:inline;}ul.pagination li a{color:#0d7377;float:left;padding:8px 16px;text-decoration:none;border: 1px solid #bbded6;margin-right: 5px;}ul.pagination li a.active{background-color:#61c0bf;color:#fff;border: 1px solid #61c0bf;}ul.pagination li a:hover:not(.active){background-color:#bbded6;}
  15. </style>
  16. </head>
  17. <body>
  18. <?php if (!isset($_SESSION['username']) || empty($_SESSION['username'])): ?>
  19. <?php header( 'Location: login.php' ) ?>
  20. <?php else : ?>
  21. <h3 style="float: left;">用户列表</h3><h4 class style="float: right;">您以成功登录
  22. <a href="javascript:;"><?=$_SESSION['username']?></a>&nbsp;
  23. <a href="dataBase.php?type=3">退出</a></h4>
  24. </div>
  25. <ul class="table1">
  26. <li class="name1">序号</li>
  27. <li class="name2">名称</li>
  28. <li class="name3">邮件</li>
  29. <li class="name4">注册日期</li>
  30. <li class="name5">操作</li>
  31. </ul>
  32. <? foreach($users as $user):?>
  33. <ul class="table2">
  34. <li class="name1"><?= $user['id']?></li>
  35. <li class="name2"><?= $user['username']?></li>
  36. <li class="name3"><?= $user['email']?></li>
  37. <li class="name4"><?= date("Y-m-d H:i:s",$user['data']) ?></li>
  38. <li class="name5"><button>修改</button> <button>删除</button></li>
  39. </ul>
  40. <?php endforeach;?>
  41. <ul class="pagination">
  42. <?php $prev = $page - 1; if($page == 1) $prev = 1; if($page != 1):?>
  43. <li><a href="?p=1'"><<</a></li>
  44. <li><a href="?p=<?=$prev ?>"><</a></li>
  45. <?endif?>
  46. <? for($i =1; $i <= $pages; $i++ ):?>
  47. <li><a class="<?php $page==$i ? print 'active' : 'null' ?>" href="?p=<?=$i?>"><?=$i?></a></li>
  48. <? endfor; ?>
  49. <?php $next = $page + 1; if($next == $page) $next = $page?>
  50. <?php if($page != $pages):?>
  51. <li><a href="?p=<?=$next?>">></a></li>
  52. <li><a href="?p=<?=$pages?>">>></a></li>
  53. <?php endif?>
  54. </ul>
  55. <div style="clear:both"></div>
  56. <?php endif ?>
  57. </body>
  58. </html>

dataBase.php //核心文件

  1. <?php
  2. session_start();
  3. $pdo = new PDO( 'mysql:host=localhost;dbname=test', 'root', 'root', [PDO::ATTR_ERRMODE=> PDO::ERRMODE_WARNING, PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC] );
  4. //分页函数
  5. //设置每页显示的数量 默认为3
  6. $num = 5;
  7. //当前页码, 默认为1
  8. $page = $_GET['p'] ?? 1;
  9. //偏移量 = ( 页码 -1 ) * 每页的显示数量
  10. $offset = ( $page - 1 ) * $num ;
  11. //获取分页数据
  12. $sql = " SELECT `id`,`username`,`password`,`email`,`c_time` FROM `user` ORDER BY `id` ASC LIMIT {$num} OFFSET {$offset} ";
  13. $users = $pdo->query( $sql )->fetchAll();
  14. //获取总页数
  15. $sql = 'SELECT COUNT(`id`) AS `sum` FROM `user`';
  16. $count = $pdo->query( $sql )->fetch()['sum'];
  17. $pages = ceil( $count/$num );
  18. //登录函数
  19. $username = !empty( $_POST['username'] ) && isset( $_POST['username'] ) ? $_POST['username']:null;
  20. $password = !empty( $_POST['password'] ) && isset( $_POST['password'] ) ? md5( $_POST['password'] ):null;
  21. $code = !empty( $_POST['code_value'] ) && isset( $_POST['code_value'] ) ? $_POST['code_value'] :null;
  22. //请求分发器 type 1登录验证 2 验证码验证 3退出登录
  23. $type = isset( $_REQUEST['type'] ) && !empty( $_REQUEST['type'] ) ? intval( $_REQUEST['type'] ):null;
  24. switch( $type )
  25. {
  26. case 1:
  27. //检测用户是否存在
  28. $sql = 'SELECT `username`,`password` FROM `user` WHERE `username`= ? AND `password`=? ; ';
  29. $stmt = $pdo->prepare( $sql );
  30. $stmt->execute( [$username, $password] );
  31. $res = $stmt->fetch();
  32. if ( $res )
  33. {
  34. //验证通过 存session
  35. $_SESSION['username'] = $res['username'];
  36. echo json_encode( array( 'status'=>1, 'msg'=>'登录成功...正在跳转' ), 320 );
  37. exit;
  38. }
  39. echo json_encode( array( 'status'=>0, 'msg'=>'用户名或密码错误' ), 320 );
  40. break;
  41. case 2:
  42. //将session中的验证码和用户提交的验证码进行核对, 当成功时提示验证码正确,并销毁之前的session值, 不成功则重新提交 strcasecmp
  43. if ( !empty( $code ) && strtolower( $_SESSION['code'] ) === strtolower( $code ) ) {
  44. $_SESSION['code'] = '';
  45. echo json_encode( ['status'=>1, 'msg'=>'验证码正确'], 320 );
  46. exit;
  47. }
  48. echo json_encode( ['status'=>0, 'msg'=>'验证码不正确'], 320 );
  49. break;
  50. // 退出登录
  51. case 3:
  52. // 清空session变量
  53. session_unset();
  54. // 删除session文件
  55. session_destroy();
  56. header( 'Location: login.php' );
  57. break;
  58. // default:
  59. // echo json_encode( ['status'=>520, 'msg'=>'非法参数访问'], 320 );
  60. // break;
  61. }

session.php //验证码页面

  1. <?php
  2. // We need the session to store the correct phrase for later check
  3. session_start();
  4. // Including the autoload ( you need to composer install in the main directory )
  5. require_once __DIR__.'/composer/vendor/autoload.php';
  6. //引用composer自动加载文件
  7. use Gregwar\Captcha\CaptchaBuilder;
  8. // Creating the captcha instance and setting the phrase in the session to store
  9. // it for check when the form is submitted
  10. $code = new CaptchaBuilder;
  11. $_SESSION['code'] = $code->getPhrase();
  12. // Setting the header to image jpeg because we here render an image
  13. header( 'Content-Type: image/jpeg' );
  14. // Running the actual rendering of the captcha image
  15. $code
  16. ->build()
  17. ->output()
  18. ;
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议