在 PHP 中,使用 header("Location: ...") 可以实现页面重定向。这是通过发送 HTTP Location 响应头来完成的。
✅ 基本语法
header("Location: http://example.com/new-page.php");
exit; // 强烈建议加上 exit 或 die()
⚠️ 注意:
📌 示例 1:简单重定向
<?php
// 重定向到首页
header("Location: /index.php");
exit;
?>
📌 示例 2:登录成功后跳转
<?php
session_start();
if ($login_success) {
$_SESSION['user'] = 'alice';
header("Location: dashboard.php");
exit;
} else {
header("Location: login.php?error=1");
exit;
}
?>
📌 示例 3:带完整 URL 的重定向(跨域)
<?php
header("Location: https://www.example.com/thank-you.html");
exit;
?>
📌 示例 4:动态拼接 URL(注意安全)
<?php
$page = $_GET['redirect'] ?? 'home.php';
// 安全建议:限制可跳转的域名或路径,防止开放重定向漏洞
$allowed_pages = ['profile.php', 'settings.php', 'home.php'];
if (in_array($page, $allowed_pages)) {
header("Location: " . $page);
exit;
} else {
header("Location: home.php");
exit;
}
?>
🔒 安全提示:不要直接使用用户输入(如 $_GET['url'])作为 Location 的值,否则可能导致 开放重定向漏洞(Open Redirect)。
❌ 错误示例(会失败)
<html>
<body>
<?php
header("Location: error.php"); // ❌ 已经输出了 HTML,headers 已发送!
?>
</body>
</html>
解决方法:确保 header() 在任何输出之前调用。
如有更多场景(如 AJAX 重定向、带状态码的重定向等),也可以继续提问!