php 实现跳转
PHP 实现页面跳转的方法
在 PHP 中实现页面跳转主要有以下几种方式:
使用 header() 函数
通过设置 HTTP 头信息实现跳转,注意必须在输出任何内容之前调用该函数:
header("Location: https://example.com");
exit(); // 确保后续代码不会执行
使用 HTML meta 标签
在 PHP 中输出 HTML 的 meta 刷新标签实现跳转:
echo '<meta http-equiv="refresh" content="0;url=https://example.com">';
使用 JavaScript 跳转
通过输出 JavaScript 代码实现跳转:
echo '<script>window.location.href="https://example.com";</script>';
使用 HTTP 状态码
对于永久重定向可以使用 301 状态码:

header("HTTP/1.1 301 Moved Permanently");
header("Location: https://example.com");
exit();
注意事项
- 使用 header() 函数前不能有任何输出,包括空格和换行符
- 跳转后建议使用 exit() 或 die() 终止脚本执行
- 相对路径和绝对路径都可以使用,但推荐使用绝对 URL
- 对于延时跳转,可以使用 meta 标签的 content 属性设置秒数
常见应用场景
登录后跳转
if ($login_success) {
header("Location: dashboard.php");
exit();
}
表单提交后跳转
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// 处理表单数据
header("Location: thank_you.php");
exit();
}
根据条件跳转不同页面
if ($user_type == 'admin') {
header("Location: admin.php");
} else {
header("Location: user.php");
}
exit();





