Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
作业标题:0825作业
作业内容:请实例演绎以下作业: 1.做一个做动态分页? 2.composer自动加载机制你了解多少? 3.请使用composer安装三方验证码库完善你的登录页面?
<?require 'pageData.php'?>
<!DOCTYPE html>
<html lang="en"></html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数据显示</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<table>
<caption>用户信息表</caption>
<thead>
<tr>
<td>编号</td>
<td>姓名</td>
<td>性别</td>
<td>创建时间</td>
<td>操作</td>
</tr>
</thead>
<tbody>
<?php foreach($users as $user):?>
<tr>
<td><?= $user['id']?></td>
<td><?= $user['uname']?></td>
<td><?= $user['gender']==1?'男':'女'?></td>
<td><?= date("Y-m-d H:m:s",$user['create_time'])?></td>
<td><button>删除</button><button>编辑</button></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<!-- 动态分页 -->
<!-- 生成动态分页条 -->
<p>
<?php $pre=$page-1;if($page!=1):?>
<a href="?p=1">首页</a>
<a href="?p=<?=$pre?>">上一页</a>
<?endif?>
<?php for ($i=1; $i <= $pages; $i++) :
$active='active' ;
// 生成一个动态的a href 属性的值
$jump = sprintf('?p=%d',$i);
$active = ($i==$page)?'active':null;
?>
<a class="<?=$active?>" href="<?=$jump?>"><?=$i?></a>
<?endfor?>
<?php $next=$page+1;if($page!=$pages):?>
<a href="?p=<?=$next?>">下一页</a>
<a href="?p=<?=$pages?>">尾页</a>
<?endif?>
</p>
</body>
</html>
PageData.php数据库连接代码以及分页相关计算逻辑
<?php
$pdo = new PDO('mysql:host=localhost;dbname=16','root','root',[PDO::ATTR_ERRMODE=> PDO::ERRMODE_WARNING,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC]);
//获取分页数据 :每页显示的数量 默认为3
$num =3;
//当前页码,默认为1
$page = $_GET['p'] ?? 1;
//计算每一页第一条记录的显示偏移量
//偏移量 = (页码 -1) \* 每页的显示数量
$offset = ($page - 1) * $num ;
//获取分页数据
$sql = " SELECT `id`,`uname`,`gender`,`create_time` FROM `user` ORDER BY `id` ASC LIMIT {$num} OFFSET {$offset} ";
//$sql = "SELECT * FROM `user` LIMIT {$offset},{$num } ";
$users = $pdo->query($sql)->fetchAll();
// print_r($users);
//获取总页数
// $sql = "SELECT CEIL(COUNT(`id`)/{$num}) AS `sum` FROM `user`";
$sql = "SELECT COUNT(`id`) AS `sum` FROM `user`";
$count = $pdo->query($sql)->fetch()['sum'];
$pages = ceil($count/$num);
// var_dump($pages);
示例演示图
2.composer自动加载机制你了解多少?
<?php
// 1.
// spl_autoload_register(function($className){
// require $className .'.php';
// });
// 2. composer 类的自动加载机制
/**
* 1. 在项目的compose.json文件中添加autoload字段 files 可以加载任意位置的类文件
* "files": [
"app/controller/Login.php",
"app/controller/User.php",
"app/controller/Auth.php"
]
修改完成以后,每添加一个新的类文件,要追加绑定并且必须要执行composer dump-autoload命令才能生效
*/
/**
* 2. 在项目的compose.json文件中添加autoload字段 classmap 类映射 实现类的批量注册
"classmap": [
"app/controller"
]
修改完成以后,必须要执行composer dump-autoload命令才能生效
*/
/**
* 3. psr-4规范 :类的命名空间与类文件所在的目录进行绑定,并且类文件名称与类名称保持一致
* 命名空间最后必须以“\”空间分隔符结束,这样以来在绑定的目录中添加新的类时 不必执行composer dump-autoload命令就能生效
*/
require 'vendor/autoload.php';
use app\controller\User;
use app\controller\Login;
use app\controller\Auth;
use app\controller\Article;
use extend\lib\Auth as libAuth;
echo User::index();
echo Login::index();
echo Auth::index();
echo Article::index();
echo libAuth::index();
{
"name": "phpcn/login",
"description": "a perfect login page with captcha",
"type": "project",
"require": {
"almasaeed2010/adminlte": "3.0.5",
"gregwar/captcha": "1.1.7"
},
"authors": [
{
"name": "imzchloe",
"email": "952637517@qq.com"
}
],
"autoload": {
"psr-4": {
"app\\controller\\": "app/controller",
"extend\\lib\\": "extend/lib"
}
}
}
3.请使用composer安装三方验证码库完善你的登录页面?
login.php前端代码
<?php
// We need the session to check the phrase after submitting
session_start();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<h2>用户登录</h2>
<table>
<tr>
<td>账户</td>
<td><input type="text" name="username"></td>
<td><span id="err_msg"></span></td>
</tr>
<tr>
<td>密码</td>
<td><input type="password" name="password"></td>
</tr>
</tr>
<tr>
<td>请输入验证码</td>
<td><input type="text" name="phrase" /></td>
<td><img src="session.php" onclick="this.src=this.src+'&k='+Math.random();"/></td>
</tr>
<tr align="center">
<td colspan="2">
<input type="button" id='btn' name="btn" value="确定">
</td>
</tr>
</table>
<script type="text/javascript" src="
https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
//const btn1=document.getElementsByName("btn");
const btn1 = document.getElementById('btn');
// alert(btn1);
// btn1.addEventListener("click",function(){
// alert("aaa");
// });
// btn1.addEventListener("click",function(){
// alert("bbb");
// });
//登录
btn1.addEventListener("click",function(){
//alert("aaa");
var data = {};
data.username = $.trim($('input[name="username"]').val());
data.password = $.trim($('input[name="password"]').val());
data.phrase = $.trim($('input[name="phrase"]').val());
data.type = 3;
if(data.username == '' || data.password == '')
{
alert('用户名或者密码不能为空哦~');
return;
}
$.post('3-doSubmit.php',data,function(res){
console.log(res);
if(res.status == 1)
{
alert(res.msg);
top.location='5-index.php';
}else{
alert(res.msg);
}
},"json")
})
</script>
</body>
</html>
接收数据并处理3-doSubmit.php代码
<?php
namespace pdo_chloe;
require 'common.php';
// 接收数据
// var_dump($_POST);
$username = !empty($_POST['username']) && isset($_POST['username']) ? $_POST['username']:null;
$password = !empty($_POST['password']) && isset($_POST['password']) ? md5($_POST['password']):null;
$gender = !empty($_POST['gender']) && isset($_POST['gender']) ? intval($_POST['gender']):null;
$phrase=(isset($_SESSION['phrase']) && $_SESSION['phrase'] === $_POST['phrase'])?$_POST['phrase']:null;
$create_time = time();
// //验证码
// if (isset($_SESSION['phrase']) && $_SESSION['phrase'] === $_POST['phrase']) {
// echo "<h1>Captcha is valid !</h1>";
// } else {
// echo "<h1>Captcha is not valid!</h1>";
// }
// // The phrase can't be used twice
// unset($_SESSION['phrase']);
//请求分发器 type 1 检查用户名重名 2注册 3 登录
$type = isset($_POST['type'])&&!empty($_POST['type']) ? intval($_POST['type']):null;
switch ($type) {
case 1:
$res = checkUname($username);
if($res)
{
echo json_encode(['status'=>0,'msg'=>'用户名已被占用'],320);
}else{
echo json_encode(['status'=>1,'msg'=>'用户名合法'],320);
}
break;
case 2:
$flag = checkUname($username);
if(!$flag){
$res = insertData($username,$password,$gender,$create_time);
if($res)
{
echo json_encode(['status'=>1,'msg'=>'注册成功'],320);
exit;
}
echo json_encode(['status'=>0,'msg'=>'注册失败'],320);
exit;
}
echo json_encode(['status'=>0,'msg'=>'请勿重复提交'],320);
break;
case 3:
$res = login($username,$password);
if ($res) {
//echo json_encode(['status'=>1,'msg'=>'用户名密码正确'], 320);
if ($phrase) {
echo json_encode(['status'=>1,'msg'=>'验证成功'], 320);
} else {
echo json_encode(['status'=>0,'msg'=>'验证码错误'], 320);
}
}else{
echo json_encode(['status'=>0,'msg'=>'用户名或密码错误'],320);
}
// if($phrase){
// echo json_encode(['status'=>1,'msg'=>'验证正确'],320);exit;
// }
// echo json_encode(['status'=>0,'msg'=>'验证码错误'],320);
break;
default:
# code...
break;
}
程序过滤验证代码common.php
<?php
session_start();
//公共模型文件
// 连接数据库
require '1-connect.php';
/**
* 检测用户注册用户名是否被占用
* param:用户名
* return : 被占用返回true 未被占用返回false
*/
function checkUname($username)
{
global $pdo;
$isOccupied = false;//默认数据库中不存在同名用户名
$sql = "SELECT `uname` FROM `user` WHERE `uname`='{$username}'";
$res = $pdo->query($sql)->fetch();
// 已存在同名昵称
if($res)
{
$isOccupied = true;
}
return $isOccupied;
}
/**
* param:用户注册 用户名 密码 性别 创建时间
* return : 注册成功返回true 失败返回false
*/
function insertData($username,$password,$gender,$create_time)
{
global $pdo;
$flag = false;
if( !empty($username) && !empty($password) && !empty($gender)){
$sql = "INSERT INTO `user` SET `uname` = '{$username}', `pwd`='{$password}', `gender` = {$gender},`create_time`={$create_time};";
$res = $pdo->exec($sql);
if($res)
{
$flag = true;
}
}
return $flag;
}
/**
* param:用户登录 用户名 密码
* return : 登录成功返回true 失败返回false
*/
function login($username,$password)
{
global $pdo;
$flag = false;
if(!empty($username) && !empty($password))
{
// 可以把它看作是想要运行的 SQL 的一种编译过的模板
// 使用问号参数占位符来构成预处理语句
$sql = "SELECT `uname`,`pwd` FROM `user` WHERE `uname`= ? AND `pwd`= ?";
// $sql = "SELECT `uname`,`pwd` FROM `user` WHERE `id`> 0 ";
// echo $sql;
// PDO::prepare — 准备要执行的语句,并返回语句对象
$stmt = $pdo->prepare($sql);
// 绑定一个PHP变量到用作预处理的SQL语句中的对应问号占位符,此变量作为引用被绑定,并只在 PDOStatement::execute() 被调用的时候才取其值。
// $stmt->bindParam(1,$username,PDO::PARAM_STR);
// $stmt->bindParam(2,$password,PDO::PARAM_STR);
// 执行一条预处理语句 成功时返回 true, 或者在失败时返回 false。
// $username = 'admin';
$stmt->execute([$username,$password]);
$res = $stmt->fetch();
// var_dump($res);
if($res)
{
$_SESSION['uname'] = $res['uname'];
$flag = true;
}
// var_dump($stmt);//object(PDOStatement)
// foreach($stmt as $v)
// {
// print_r($v);
// }
// die;
}
return $flag;
}
数据库连接代码 1-connect.php
<?php
namespace connect_chloe;
use PDO;
$config = require __DIR__ .'\\config\\database.php';
extract($config);
// dsn data source name 包括pDO驱动名称 主机名 端口号 数据库名称
$dsn = sprintf('%s:host=%s;port=%d;dbname=%s',$type,$host,$port,$dbname);
try {
$pdo = new PDO($dsn,$username,$password,[PDO::ATTR_ERRMODE=>PDO::ERRMODE_WARNING]);
// var_dump($pdo);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
} catch (\Exception $e) {
die('Connection error : ' . $e->getMessage());
}
第三方验证码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__.'/../vendor/autoload.php';
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
$captcha = new CaptchaBuilder;
$_SESSION['phrase'] = $captcha->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
$captcha
->build()
->output()
;
实例图