本文详解如何使用 mysqli 预处理语句安全实现 php 用户登录,并正确执行登录成功后的页面跳转;重点修复常见重定向失效问题(如会话未启动、赋值误用、响应头发送异常等)。
在基于 MySQLi 的 PHP 登录系统中,header("Location: ...") 重定向失败是初学者高频问题。从你提供的代码来看,逻辑结构基本合理,但存在一个关键语法错误和多个潜在运行时隐患,直接导致登录后无法跳转至 ../index.php?login=success。
在原始代码中:
else if ($pwdCheck = true) {此处使用了单等号 =(赋值),而非双等号 == 或三等号 ===(比较)。这行代码实际效果是:将 true 赋值给 $pwdCheck,并始终返回 true,导致该分支恒成立——不仅掩盖了密码校验逻辑,还可能干扰后续流程判断。
✅ 正确写法应为:
else if ($pwdCheck === true) { // 强类型比较,更安全或更简洁、更符合 PHP 惯用法的写法:
else { // 因为 $pwdCheck 是 password_verify() 的布尔返回值,且前面已排除 false 分支session_start() 必须在任何输出前调用
若 dbh.inc.php 或其他引入文件中存在空格、BOM 字符或 echo/print,会导致“Headers already sent”警告,使 header() 失效。建议在登录脚本最顶部立即启动会话:
重定向路径需绝对可靠
../index.php 依赖当前脚本所在目录层级。若部署路径变化,易出错。推荐统一使用根相对路径或完整 URL:
header("Location: /index.php?login=success"); // 根路径(推荐)
// 或
header("Location: https://yoursite.com/index.php?login=success");避免多余输出与缓冲干扰
确保 .php 文件无 UTF-8 BOM,且 exit() 后无任何字符(包括换行、空格)。可在 header() 后添加 exit() 并检查是否被意外注释。
;
if (empty($mailuid) || empty($password)) {
header("Location: /index.php?error=emptyfields");
exit();
}
$sql = "SELECT * FROM users WHERE uidUsers = ? OR emailUsers = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: /index.php?error=sqlerror");
exit();
}
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
if (password_verify($password, $row['pwdUsers'])) {
// ✅ 密码正确:设置会话并跳转
$_SESSION['userId'] = (int)$row['idUsers'];
$_SESSION['userUid'] = htmlspecialchars($row['uidUsers']); // 防 XSS
header("Location: /index.php?login=success");
exit();
} else {
header("Location: /index.php?error=wrongpwd");
exit();
}
} else {
header("Location: /index.php?error=nouser");
exit();
}
} else {
// 非 POST 请求,拒绝访问
header("Location: /index.php");
exit();
}开启错误报告(开发环境):在脚本开头添加
ini_set('display_errors', 1);
error_reporting(E_ALL);可快速捕获 Headers already sent 等致命警告。
验证重定向是否生效:在 index.php 中临时加入:
✅ 登录成功!会话已建立。
安全加固:
遵循以上修正与规范,你的登录重定向功能将稳定可靠,同时兼顾安全性与可维护性。