php如何实现页面跳转
PHP 实现页面跳转的方法
使用 header() 函数
header() 函数是 PHP 中最常用的页面跳转方式,通过发送 HTTP 头部信息实现跳转。跳转前不能有任何输出(包括空格、HTML 标签或 PHP 错误信息),否则会报错。
header("Location: https://example.com/target-page.php");
exit(); // 确保跳转后终止脚本执行
如果需要延迟跳转,可以结合 refresh 参数:
header("Refresh: 3; url=https://example.com/target-page.php");
echo "3秒后跳转...";
使用 HTML 的 <meta> 标签
如果已经输出了内容,无法使用 header(),可以通过 HTML 的 <meta> 标签实现跳转:
echo '<meta http-equiv="refresh" content="3;url=https://example.com/target-page.php">';
使用 JavaScript 跳转
通过 echo 输出 JavaScript 代码实现跳转:
echo '<script>window.location.href = "https://example.com/target-page.php";</script>';
结合 HTTP 状态码跳转
某些场景下可能需要返回特定的 HTTP 状态码(如 301 永久重定向):
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://example.com/new-page.php");
exit();
注意事项
header()前不能有输出:确保调用header()前没有输出任何内容(包括 PHP 错误或空格)。- 绝对路径与相对路径:建议使用完整 URL 避免路径问题。
exit()或die():跳转后建议立即终止脚本,防止后续代码执行。
示例:带参数的跳转
若需传递参数,可通过 URL 拼接:

$user_id = 123;
header("Location: profile.php?id=" . urlencode($user_id));
exit();






