php怎样实现页面跳转页面跳转页面
PHP 页面跳转的实现方法
使用 header() 函数实现跳转header() 函数是 PHP 中最常用的跳转方法,通过发送 HTTP 头信息实现页面重定向。
示例代码:
header("Location: https://example.com/target-page.php");
exit(); // 确保后续代码不会执行
注意:header() 必须在输出任何内容之前调用,否则会报错。
通过 HTML <meta> 标签实现跳转
如果已经输出了 HTML 内容,可以使用 <meta> 标签实现跳转。
示例代码:

echo '<meta http-equiv="refresh" content="0;url=https://example.com/target-page.php">';
使用 JavaScript 跳转
如果需要在某些条件触发后跳转,可以使用 JavaScript。
示例代码:
echo '<script>window.location.href = "https://example.com/target-page.php";</script>';
带延迟的跳转
通过 header() 或 <meta> 标签可以设置延迟跳转。
示例代码(3 秒后跳转):

header("Refresh: 3; url=https://example.com/target-page.php");
echo "3 秒后将跳转到目标页面";
带参数的跳转
可以在跳转 URL 中附加参数,实现数据传递。
示例代码:
$userId = 123;
header("Location: target-page.php?user_id=$userId");
exit();
条件跳转
根据逻辑判断决定是否跳转。
示例代码:
if ($isLoggedIn) {
header("Location: dashboard.php");
} else {
header("Location: login.php");
}
exit();
注意事项
- 使用
header()时确保没有输出任何内容(包括空格和空行)。 - 跳转后建议使用
exit()或die()终止脚本执行,避免后续代码意外运行。 - 对于需要 SEO 友好的跳转,建议使用 301 或 302 状态码。
示例(301 永久重定向):header("HTTP/1.1 301 Moved Permanently"); header("Location: https://example.com/new-page.php"); exit();






