composer类的自动加载机制
页面文件引用:require 'vendor/lotoload.php';
在composer.json添加autoload字段,共有3三形式,推荐使用第3种方式:psr-4规范.添加完后要在终端中执行 composer dump-autoload这样做的自动加载才会生效
1.在composer.json添加autoload字段files
"autoload":{
"files": [
"add/controller/Login.php",
"add/controller/User.php"
]
}
2.在composer.json添加autoload字段classmap,
"autoload":{
"classmap": [
"add/controller/"
]
}
3.psr-4规范,推荐使用
类的命名空间与类文件所在目录进行绑定,并且类文件名称与类名称保持一致,使用psr-4命名空间最后,必须以”\”空间分隔符结束,这样以来在绑定的目录中添加新类时,不必执行 composer dump-autoload操作就能生效
"autoload":{
"psr-4": {
"app\\controller\\":"app/controller",
"extend\\lib\\":"extend/lib"
}
}
实战:
使用composer安装三方验证码库完善登录页面,登录后转到用户列表页面,在这个页面做一个动态分页
除了composer相关的文件及第三方验证码库文件比较多就不贴出来了,贴出来所写的几个文件
- login.php //登录界面
- user.php //用户列表界面
- dataBase.php //核心文件
- session.php //验证码页面
先来看个实际演示
login.php登录界面
<?php
session_start();
require_once __DIR__.'/composer/vendor/autoload.php';
use Gregwar\Captcha\PhraseBuilder;
?>
<!DOCTYPE html>
<html lang = 'en'>
<head>
<meta charset = 'utf-8' />
<title>用户登录</title>
<meta name = 'viewport' content = 'width=device-width, initial-scale=1.0' />
<meta name = 'description' content = 'Premium Bootstrap 4 Landing Page Template' />
<meta name = 'keywords' content = 'bootstrap 4, premium, marketing, multipurpose' />
<meta content = 'Themesdesign' name = 'author' />
<!-- css -->
<link href = 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css' rel = 'stylesheet' type = 'text/css' />
<!--Themify Icon -->
</head>
<body>
<section>
<div class = 'container'>
<div class = 'row justify-content-center mt-4'>
<div class = 'col-lg-4'>
<nav>
<?php if (!isset($_SESSION['username']) || empty($_SESSION['username'])): ?>
<div class = 'bg-white p-4 rounded'>
<div class = 'text-center'>
<h4 class = 'fw-bold mb-3'>用户登录</h4>
</div>
<div class = 'row login-form'>
<div class = 'col-lg-12 mt-2'>
<input type="text" name="username" class = 'form-control' placeholder="用户名" autofocus>
</div>
<div class = 'col-lg-12 mt-2'>
<input type="password" name="password" class = 'form-control' placeholder="请输入密码" >
</div>
<div class = 'col-lg-12 mt-2'>
<input type = 'code' class = 'form-control' placeholder = '验证码' required = '' name="code" id="code" style = 'float: left; width:55%;'>
<label class = 'form-check-label'>
<img src = 'session.php' onclick="this.src='session.php?id='+ Math.random();" height = '40px' style="margin: auto 10px;vertical-align: bottom; cursor:pointer" alt = '点击刷新'>
</label>
<span id="error_msg"> </span>
</div>
<div class = 'col-lg-12 mt-2'>
<div class = 'form-check'>
<input class = 'form-check-input' style = 'color: red;' type = 'checkbox' value = '' id = 'flexCheckDefault'>
<label class = 'form-check-label' for = 'flexCheckDefault'>
记住
</label>
</div>
</div>
<div class = 'col-lg-12 mt-3 mb-4'>
<button type ="button" class = 'btn btn-primary w-100' name="btn">登录</button>
</div>
<div class = 'txet-center'>
<p class = 'mb-0 mt-2 text-center'>
<a href = 'reg.php' class = 'text-dark fw-bold'>注册用户</a>
</p>
</div>
</div>
</div>
<?php else : ?>
<div class = 'text-center'>
<h4 class = 'fw-bold mb-3'>您以成功登录</h4>
<a href="javascript:;"><?=$_SESSION['username']?></a>
<a href="dataBase.php?type=3">退出</a>
</div>
<?php endif ?>
</nav>
</div>
</div>
</div>
</section>
<!-- javascript -->
<script type = 'text/javascript' src = "
https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
//登录
$('button[name="btn"]').click(function(){
var data = {};
data.username =$.trim($('input[name="username"]').val()) ;
data.password = $.trim($('input[name="password"]').val());
data.type = 1;
var code = $.trim($('input[name="code"]').val())
if(data.username == '' || data.password == '' || code == '')
{
alert('必选项不能为空哦~');
return;
}
$.post('dataBase.php',data,function(res){
if(res.status == 1)
{
alert(res.msg);
//用户验证通过 跳转用户列表页
setTimeout(()=>location.href = 'User.php',500);
}else{
alert(res.msg);
}
},"json")
})
//使用ajax异步验证 验证码
$('input[name="code"]').keyup(function(){
var data={};
data.code_value = $.trim($(this).val());
data.type = 2;
if(data.code_value == '')
{
$("#error_msg").html("<span style='color:green'>验证码不能为空</span>")
return;
}
$.post('dataBase.php',data,function(res){
if(res.status == 1)
{
$("#error_msg").html("<span style='color:green'>验证码正确</span>")
}else{
$("#error_msg").html("<span style='color:red'>验证码错误</span>")
}
},"json")
})
</script>
</body>
</html>
user.php //用户列表界面
<?session_start()?>
<? require 'dataBase.php' ?>
<!DOCTYPE HTML>
<html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>用户修改</title>
<style type="text/css">
/*节省空间CSS给压缩了*/
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;}
</style>
</head>
<body>
<?php if (!isset($_SESSION['username']) || empty($_SESSION['username'])): ?>
<?php header( 'Location: login.php' ) ?>
<?php else : ?>
<h3 style="float: left;">用户列表</h3><h4 class style="float: right;">您以成功登录
<a href="javascript:;"><?=$_SESSION['username']?></a>
<a href="dataBase.php?type=3">退出</a></h4>
</div>
<ul class="table1">
<li class="name1">序号</li>
<li class="name2">名称</li>
<li class="name3">邮件</li>
<li class="name4">注册日期</li>
<li class="name5">操作</li>
</ul>
<? foreach($users as $user):?>
<ul class="table2">
<li class="name1"><?= $user['id']?></li>
<li class="name2"><?= $user['username']?></li>
<li class="name3"><?= $user['email']?></li>
<li class="name4"><?= date("Y-m-d H:i:s",$user['data']) ?></li>
<li class="name5"><button>修改</button> <button>删除</button></li>
</ul>
<?php endforeach;?>
<ul class="pagination">
<?php $prev = $page - 1; if($page == 1) $prev = 1; if($page != 1):?>
<li><a href="?p=1'"><<</a></li>
<li><a href="?p=<?=$prev ?>"><</a></li>
<?endif?>
<? for($i =1; $i <= $pages; $i++ ):?>
<li><a class="<?php $page==$i ? print 'active' : 'null' ?>" href="?p=<?=$i?>"><?=$i?></a></li>
<? endfor; ?>
<?php $next = $page + 1; if($next == $page) $next = $page?>
<?php if($page != $pages):?>
<li><a href="?p=<?=$next?>">></a></li>
<li><a href="?p=<?=$pages?>">>></a></li>
<?php endif?>
</ul>
<div style="clear:both"></div>
<?php endif ?>
</body>
</html>
dataBase.php //核心文件
<?php
session_start();
$pdo = new PDO( 'mysql:host=localhost;dbname=test', 'root', 'root', [PDO::ATTR_ERRMODE=> PDO::ERRMODE_WARNING, PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC] );
//分页函数
//设置每页显示的数量 默认为3
$num = 5;
//当前页码, 默认为1
$page = $_GET['p'] ?? 1;
//偏移量 = ( 页码 -1 ) * 每页的显示数量
$offset = ( $page - 1 ) * $num ;
//获取分页数据
$sql = " SELECT `id`,`username`,`password`,`email`,`c_time` FROM `user` ORDER BY `id` ASC LIMIT {$num} OFFSET {$offset} ";
$users = $pdo->query( $sql )->fetchAll();
//获取总页数
$sql = 'SELECT COUNT(`id`) AS `sum` FROM `user`';
$count = $pdo->query( $sql )->fetch()['sum'];
$pages = ceil( $count/$num );
//登录函数
$username = !empty( $_POST['username'] ) && isset( $_POST['username'] ) ? $_POST['username']:null;
$password = !empty( $_POST['password'] ) && isset( $_POST['password'] ) ? md5( $_POST['password'] ):null;
$code = !empty( $_POST['code_value'] ) && isset( $_POST['code_value'] ) ? $_POST['code_value'] :null;
//请求分发器 type 1登录验证 2 验证码验证 3退出登录
$type = isset( $_REQUEST['type'] ) && !empty( $_REQUEST['type'] ) ? intval( $_REQUEST['type'] ):null;
switch( $type )
{
case 1:
//检测用户是否存在
$sql = 'SELECT `username`,`password` FROM `user` WHERE `username`= ? AND `password`=? ; ';
$stmt = $pdo->prepare( $sql );
$stmt->execute( [$username, $password] );
$res = $stmt->fetch();
if ( $res )
{
//验证通过 存session
$_SESSION['username'] = $res['username'];
echo json_encode( array( 'status'=>1, 'msg'=>'登录成功...正在跳转' ), 320 );
exit;
}
echo json_encode( array( 'status'=>0, 'msg'=>'用户名或密码错误' ), 320 );
break;
case 2:
//将session中的验证码和用户提交的验证码进行核对, 当成功时提示验证码正确,并销毁之前的session值, 不成功则重新提交 strcasecmp
if ( !empty( $code ) && strtolower( $_SESSION['code'] ) === strtolower( $code ) ) {
$_SESSION['code'] = '';
echo json_encode( ['status'=>1, 'msg'=>'验证码正确'], 320 );
exit;
}
echo json_encode( ['status'=>0, 'msg'=>'验证码不正确'], 320 );
break;
// 退出登录
case 3:
// 清空session变量
session_unset();
// 删除session文件
session_destroy();
header( 'Location: login.php' );
break;
// default:
// echo json_encode( ['status'=>520, 'msg'=>'非法参数访问'], 320 );
// break;
}
session.php //验证码页面
<?php
// We need the session to store the correct phrase for later check
session_start();
// Including the autoload ( you need to composer install in the main directory )
require_once __DIR__.'/composer/vendor/autoload.php';
//引用composer自动加载文件
use Gregwar\Captcha\CaptchaBuilder;
// Creating the captcha instance and setting the phrase in the session to store
// it for check when the form is submitted
$code = new CaptchaBuilder;
$_SESSION['code'] = $code->getPhrase();
// Setting the header to image jpeg because we here render an image
header( 'Content-Type: image/jpeg' );
// Running the actual rendering of the captcha image
$code
->build()
->output()
;