php如何实现页面跳转
使用header函数实现跳转
通过header函数发送HTTP头信息实现跳转,需确保在调用前无任何输出(包括空格或HTML标签)。跳转后建议用exit终止脚本执行。
header("Location: https://example.com/target_page.php");
exit;
使用HTML的meta标签跳转
适用于无法使用header的情况(如已有输出),通过HTML的<meta>标签设置自动跳转。
echo '<meta http-equiv="refresh" content="0;url=https://example.com/target_page.php">';
使用JavaScript跳转
通过window.location实现前端跳转,灵活性较高,适合需要条件判断的场景。
echo '<script>window.location.href = "https://example.com/target_page.php";</script>';
延迟跳转的实现
结合header或meta标签设置延迟时间(单位为秒),例如3秒后跳转:
// 使用header(需浏览器支持Refresh头)
header("Refresh: 3; url=https://example.com/target_page.php");
echo "3秒后跳转...";
// 或使用meta标签
echo '<meta http-equiv="refresh" content="3;url=https://example.com/target_page.php">';
条件跳转示例
根据逻辑判断决定跳转目标,例如用户登录验证:
if ($isLoggedIn) {
header("Location: /dashboard.php");
} else {
header("Location: /login.php");
}
exit;
注意事项
header跳转前不能有任何输出,否则会触发“Headers already sent”错误。- 跳转URL可以是绝对路径或相对路径,但推荐使用完整URL以避免歧义。
- 涉及敏感操作(如支付完成跳转)应结合服务器端验证,避免前端跳转被篡改。







