You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过header(Location:)传递多URL参数致WordPress页面无法访问

问题分析:header跳转多参数导致WordPress页面404

问题现象

  • 使用header("Location:")传递3个参数时,WordPress提示「页面未找到」,但浏览器地址栏显示的URL格式正确;仅传递单个参数时页面可正常访问。
  • 生成的目标URL示例:https://somesite.ca/somepage?id=yes&name=somename&email=someemail

原代码

<?php
if(isset($_GET['user_email']) && isset($_GET['name'])){
    $email = $_GET['user_email'];
    $name = $_GET['name'];
    //authenticate the request and send the data to DB or write to text file   
}
$sql = "SELECT * FROM wpeu_users WHERE user_email = '$email'";
$result = $conn->query($sql);

if (mysqli_num_rows($result) == 0) {
    echo "That email address is not in the database.";
    $id = "no";
    header("Location: https://somesite.ca?id=no#info");
    exit();  
} else { 
    echo "that email address is in the database";
    $id="yes";
    $url_param = "id=$id&name=$name&email=$email";
    header("Location: https://somesite.ca/welcome-back?$url_param");
    exit();
}

$conn->close();
?>

问题根源

  1. URL参数未编码:直接拼接$name、$email到URL中,若参数值包含特殊字符(如空格、@、&、中文等),会破坏URL的合法结构,导致WordPress路由解析器无法正确识别页面,返回404。
  2. header前存在输出:代码中header()执行前有echo语句,虽然后续用exit()终止,但如果输出了内容(包括不可见的空格),会导致HTTP头无法正常发送,可能引发隐性跳转异常。
  3. 严重SQL注入风险:直接将用户输入的$email拼接到SQL语句中,恶意用户可通过构造特殊邮箱值执行任意SQL语句,破坏数据库。

解决方案

  1. 正确编码URL参数:使用http_build_query()自动生成编码后的参数串,避免手动拼接出错:
    $url_param = http_build_query([
        'id' => $id,
        'name' => $name,
        'email' => $email
    ]);
    
  2. 移除header前的输出:删除所有echo语句,确保header()执行前没有任何内容输出。
  3. 修复SQL注入:使用mysqli预处理语句绑定参数,安全查询数据库:
    $sql = "SELECT * FROM wpeu_users WHERE user_email = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();
    

修正后的完整代码

<?php
if(isset($_GET['user_email']) && isset($_GET['name'])){
    $email = $_GET['user_email'];
    $name = $_GET['name'];
    //authenticate the request and send the data to DB or write to text file   
}

// 使用预处理语句安全查询
$sql = "SELECT * FROM wpeu_users WHERE user_email = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

if (mysqli_num_rows($result) == 0) {
    $id = "no";
    header("Location: https://somesite.ca?id=no#info");
    exit();  
} else { 
    $id="yes";
    // 自动生成编码后的参数串
    $url_param = http_build_query([
        'id' => $id,
        'name' => $name,
        'email' => $email
    ]);
    header("Location: https://somesite.ca/welcome-back?$url_param");
    exit();
}

$conn->close();
?>

内容的提问来源于stack exchange,提问作者Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 06:30:50