php实现网页跳转
使用header函数实现跳转
PHP中可以通过header()函数发送HTTP头信息实现页面跳转。该方法必须在任何实际输出之前调用,否则会报错。
header("Location: https://www.example.com");
exit(); // 确保跳转后立即终止脚本执行
使用HTML的meta标签跳转
若已输出HTML内容无法使用header(),可通过HTML的<meta>标签实现延迟跳转。
echo '<meta http-equiv="refresh" content="0;url=https://www.example.com">';
使用JavaScript跳转
通过输出JavaScript代码实现客户端跳转,适用于需要条件判断的场景。
echo '<script>window.location.href="https://www.example.com";</script>';
延迟跳转实现
通过header()函数结合refresh参数可实现延迟跳转,单位秒。
header("Refresh: 5; url=https://www.example.com");
echo '5秒后将自动跳转...';
条件跳转示例
根据条件动态决定跳转目标,例如登录验证场景。
if ($login_success) {
header("Location: dashboard.php");
} else {
header("Location: login.php?error=1");
}
exit();
相对路径跳转
跳转目标可使用相对路径,基于当前脚本位置解析。
header("Location: ../user/profile.php"); // 上级目录下的文件
跳转时传递参数
在跳转URL中附加查询字符串传递数据。
$user_id = 123;
header("Location: profile.php?uid=" . urlencode($user_id));
注意事项
使用header()跳转前确保无任何输出(包括空格和BOM头)。可结合ob_start()启用输出缓冲避免报错。
ob_start();
// 中间代码可能有输出
header("Location: target.php");
ob_end_flush();






