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

PHP如何将当前活跃页面设置为header跳转的Location目标地址

解决方案

步骤1:在发布表单中新增来源标识字段

首页和「我的帖子」页面的发布表单内,添加如下隐藏字段,用于传递当前页面的地址:

<input type="hidden" name="redirect_to" value="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>">

使用htmlspecialchars处理参数可避免XSS安全风险

步骤2:修改后端重定向逻辑

替换原硬编码的跳转代码,改为读取表单传递的来源地址,同时保留失败状态参数的传递逻辑:

// 读取来源地址,无参数时兜底跳转到首页
$redirectUrl = $_POST['redirect_to'] ?? '../home.php';
// 安全校验:仅允许跳转到站内指定页面,避免恶意跳转风险
$allowedPage = ['../home.php', '../my_posts.php']; // 请替换为你实际的「我的帖子」页面路径
if (!in_array($redirectUrl, $allowedPage)) {
    $redirectUrl = '../home.php';
}

if ($result == TRUE) {
    header("Location: " . $redirectUrl);
} else {
    // 兼容原地址已有参数的场景,正确拼接失败标识
    $splitChar = str_contains($redirectUrl, '?') ? '&' : '?';
    header("Location: " . $redirectUrl . $splitChar . "failed");
}
exit; // 重定向后必须终止后续代码执行

如果使用PHP7及以下版本,可将str_contains($redirectUrl, '?')替换为strpos($redirectUrl, '?') !== false

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:54:05