🗣 Wd提问: php分页安全
🤖 Ai回答: PHP分页安全是一个重要的话题,主要涉及防止SQL注入、XSS攻击等安全问题。以下是完整的安全分页实现方案:
1、基础安全分页类
php
<?php
class SecurePagination {
private $pdo;
private $table;
private $perPage;
private $currentPage;
private $totalRecords;
public function __construct($pdo, $table, $perPage = 10) {
$this-pdo = $pdo;
$this-table = $this-sanitizeTableName($table);
$this-perPage = max(1, min(100, (int)$perPage)); // 限制每页记录数
$this-currentPage = max(1, (int)($_GET['page'] ?? 1));
}
/
* 安全的表名验证
*/
private function sanitizeTableName($table) {
// 只允许字母、数字和下划线
if (!preg_match('/^[a-zA-Z0-9_]+$/', $table)) {
throw new InvalidArgumentException('Invalid table name');
}
return $table;
}
/
* 获取总记录数
*/
public function getTotalRecords($where = '', $params = []) {
try {
$sql = SELECT COUNT(*) FROM {$this-table};
if ($where) {
$sql .= WHERE {$where};
}
$stmt = $this-pdo-prepare($sql);
$stmt-execute($params);
$this-totalRecords = $stmt-fetchColumn();
return $this-totalRecords;
} catch (PDOException $e) {
error_log(Database error: 、$e-getMessage());
return 0;
}
}
/
* 获取分页数据
*/
public function getData($columns = '*', $where = '', $params = [], $orderBy = '') {
$offset = ($this-currentPage 1) * $this-perPage;
$sql = SELECT {$columns} FROM {$this-table};
if ($where) {
$sql .= WHERE {$where};
}
if ($orderBy) {
// 验证排序字段和方向
$orderBy = $this-sanitizeOrderBy($orderBy);
$sql .= ORDER BY {$orderBy};
}
$sql .= LIMIT :limit OFFSET :offset;
try {
$stmt = $this-pdo-prepare($sql);
// 绑定用户参数
foreach ($params as $key = $value) {
$stmt-bindValue($key, $value);
}
// 绑定分页参数
$stmt-bindValue(':limit', $this-perPage, PDO::PARAM_INT);
$stmt-bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt-execute();
return $stmt-fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log(Database error: 、$e-getMessage());
return [];
}
}
/
* 安全的排序字段验证
*/
private function sanitizeOrderBy($orderBy) {
// 允许的排序字段列表
$allowedFields = ['id', 'name', 'created_at', 'updated_at'];
$allowedDirections = ['ASC', 'DESC'];
// 解析排序字符串
$parts = explode(' ', trim($orderBy), 2);
$field = $parts[0];
$direction = isset($parts[1]) ? strtoupper($parts[1]) : 'ASC';
// 验证字段和方向
if (!in_array($field, $allowedFields)) {
$field = 'id'; // 默认排序字段
}
if (!in_array($direction, $allowedDirections)) {
$direction = 'ASC'; // 默认排序方向
}
return {$field} {$direction};
}
/
* 生成分页链接
*/
public function generateLinks($baseUrl = '', $additionalParams = []) {
if (!$this-totalRecords) {
return '';
}
$totalPages = ceil($this-totalRecords / $this-perPage);
if ($totalPages <= 1) {
return '';
}
$links = '<div class=pagination';
// 上一页
if ($this-currentPage 1) {
$prevPage = $this-currentPage 1;
$links .= $this-createLink($prevPage, '« 上一页', $baseUrl, $additionalParams);
}
// 页码
$start = max(1, $this-currentPage 2);
$end = min($totalPages, $this-currentPage + 2);
for ($i = $start; $i <= $end; $i++) {
if ($i == $this-currentPage) {
$links .= <span class='current'{$i}</span;
} else {
$links .= $this-createLink($i, $i, $baseUrl, $additionalParams);
}
}
// 下一页
if ($this-currentPage < $totalPages) {
$nextPage = $this-currentPage + 1;
$links .= $this-createLink($nextPage, '下一页 »', $baseUrl, $additionalParams);
}
$links .= '</div';
return $links;
}
/
* 创建安全的分页链接
*/
private function createLink($page, $text, $baseUrl, $additionalParams) {
$params = array_merge($additionalParams, ['page' = $page]);
$queryString = http_build_query($params);
$url = $baseUrl ?: $_SERVER['PHP_SELF'];
if ($queryString) {
$url .= '?' 、$queryString;
}
// HTML转义防止XSS
$escapedUrl = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
$escapedText = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
return <a href='{$escapedUrl}'{$escapedText}</a;
}
/**
* 获取分页信息
*/
public function getPaginationInfo() {
if (!$this-totalRecords) {
return [
'current_page' = 0,
'per_page' = 0,
'total_records' = 0,
'total_pages' = 0,
'from' = 0,
'to' = 0
];
}
$totalPages = ceil($this-totalRecords / $this-perPage);
$from = ($this-currentPage 1) * $this-perPage + 1;
$to = min($this-currentPage * $this-perPage, $this-totalRecords);
return [
'current_page' = $this-currentPage,
'per_page' = $this-perPage,
'total_records' = $this-totalRecords,
'total_pages' = $totalPages,
'from' = $from,
'to' = $to
];
}
}
2、使用示例
php
<?php
// 数据库连接
try {
$pdo = new PDO('mysql:host=localhost;dbname=test', $username, $password, [
PDO::ATTR_ERRMODE = PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE = PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES = false
]);
} catch (PDOException $e) {
die(数据库连接失败: 、$e-getMessage());
}
// 创建分页对象
$pagination = new SecurePagination($pdo, 'users', 10);
// 搜索条件(如果有的话)
$search = $_GET['search'] ?? '';
$where = '';
$params = [];
if ($search) {
$where = name LIKE :search OR email LIKE :search;
$params[':search'] = %{$search}%;
}
// 获取总记录数
$totalRecords = $pagination-getTotalRecords($where, $params);
// 获取当前页数据
$data = $pagination-getData('*', $where, $params, 'created_at DESC');
// 获取分页信息
$pageInfo = $pagination-getPaginationInfo();
// 生成分页链接
$baseUrl = $_SERVER['PHP_SELF'];
$additionalParams = [];
if ($search) {
$additionalParams['search'] = $search;
}
$paginationLinks = $pagination-generateLinks($baseUrl, $additionalParams);
?
<!DOCTYPE html
<html
<head
<title安全分页示例</title
<style
.pagination { margin: 20px 0; text-align: center; }
.pagination a, .pagination span {
display: inline-block;
padding: 5px 10px;
margin: 0 2px;
border: 1px solid ddd;
text-decoration: none;
}
.pagination .current {
background-color: 007cba;
color: white;
}
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid ddd; padding: 8px; text-align: left; }
th { background-color: f2f2f2; }
</style
📣 商家广告:





0
IP地址: 54.123.203.133
搜索次数: 5
提问时间: 2025-10-30 15:50:27
🛒 域名购买:
279.net.cn
4.bj.cn
jamctr.com
ltkj.net
45.gold
jjxs.cn
qppp.com.cn
cisou.com.cn
sou.gg
jldj.cn
❓️ 热门提问:
安卓搭建web服务器
金海威 香港上市
8国外vps免费
商城域名注册局官网
.com域名注册价格
vps搭建ss违法吗知乎
租服务器托管
cdn加速 国际
长沙机房托管
如何加入服务器
豌豆Ai站群搜索引擎系统
🌐 域名评估:
you.ai
mi.gx.cn
20.hk
ao.cq.cn
yg.com.cn
kqnm.cn
ap.cq.cn
juhc.cn
aaaa.hl.cn
krgi.cn
⛏ 最新挖掘:
凯里酸汤鱼
贵阳烤脑花
都匀毛尖茶
花溪牛肉粉
贵阳烤生蚝
贵阳烤豆腐
贵阳纸包鱼
贵阳特色菜
🖌 热门作画:
🤝 关于我们:
豌豆Ai
域名
建站
站群
留痕
推广
评估
源码
开发Ai
工具
日记
价格
加盟
广告
流量
留言
联系
🗨 加入群聊:
🔗 友情链接:
常用软件
台湾网站搜尋
ai提问
🧰 站长工具:
Ai工具 whois查询 搜索
📢 温馨提示:本站所有问答由Ai自动创作,内容仅供参考,若有误差请用“联系”里面信息通知我们人工修改或删除。
👉 技术支持:本站由豌豆Ai提供技术支持,使用的最新版:《豌豆Ai站群搜索引擎系统 V.25.10.25》搭建本站。