
本文详解为何将 post() 函数直接用于
本文详解为何将 post() 函数直接用于
✅ 步骤二:创建独立处理器(includes/post_handler.php)
<?php require_once 'dbh.inc.php'; // 确保数据库连接可用
require_once 'post.inc.php'; // 加载函数定义
// ✅ 关键:仅当收到 POST 请求时才调用函数
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['postSubmit'])) {
post($conn); // 此处调用才真正有意义
} else {
header('Location: ../home.php?error=invalid_request');
exit();
}✅ 步骤三:优化 post.inc.php(修复逻辑缺陷)
原函数存在严重问题:
- 重复调用 session_start()(已在 post.php 启动);
- while ($PostIDDuplicate = true) 是赋值而非比较,造成无限循环;
- 缺少对关键变量(如 $_SESSION['UserID'])的存在性校验。
修正后的 post() 函数示例:
function post($conn) {
// ✅ 避免重复 session_start()
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// ✅ 严格校验会话与输入
if (!isset($_SESSION['UserID']) || empty($_POST['Text'])) {
header('Location: ../home.php?error=access_denied');
exit();
}
$UserID = $_SESSION['UserID'];
$Date = $_POST['Date'] ?? date('Y-m-d H:i:s');
$Text = trim($_POST['Text']);
$SectionID = 1;
// ✅ 修复死循环:使用 !== false 和 proper condition
$PostIDLength = 11;
$chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$PostID = null;
$attempts = 0;
do {
$PostID = substr(str_shuffle($chars), 0, $PostIDLength);
$stmt = mysqli_prepare($conn, "SELECT 1 FROM PostTable WHERE PostID = ?");
mysqli_stmt_bind_param($stmt, "s", $PostID);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
} while (mysqli_num_rows($result) > 0 && ++$attempts = 100) {
header('Location: ../home.php?error=id_generation_failed');
exit();
}
$stmt = mysqli_prepare($conn, "INSERT INTO PostTable (PostID, UserID, SectionID, Date, Text) VALUES (?, ?, ?, ?, ?)");
mysqli_stmt_bind_param($stmt, "ssiss", $PostID, $UserID, $SectionID, $Date, $Text);
if (mysqli_stmt_execute($stmt)) {
header('Location: ../home.php?success=post_created');
} else {
header('Location: ../home.php?error=db_error');
}
exit();
}
⚠️ 注意事项总结
- ❌ 禁止在 HTML 属性中执行含重定向/输出的函数(如 action="= post($conn) ?>");
- ✅ action 值应为静态 URL 路径(如 post_handler.php),由该脚本决定是否调用 post();
- ✅ 所有数据库操作前必须校验 $_POST 和会话状态;
- ✅ 使用 mysqli_prepare() + 参数绑定防御 SQL 注入;
- ✅ 生成唯一 ID 时设置最大尝试次数,避免潜在死锁。
通过这种清晰的职责分离,你既能复用 post() 函数,又能确保流程符合 PHP 服务端执行模型——这才是可维护、安全且符合最佳实践的实现方式。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!










