PHP 重定向是指将用户从一个页面自动跳转到另一个页面的过程。这通常通过修改 HTTP 响应头中的 Location 字段来实现。
<?php
// 永久重定向
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.example.com/new-page.php");
// 临时重定向
header("HTTP/1.1 302 Found");
header("Location: https://www.example.com/temporary-page.php");
// 自定义重定向
if (isset($_SESSION['user_id'])) {
header("Location: https://www.example.com/dashboard.php");
} else {
header("Location: https://www.example.com/login.php");
}
?>header() 函数在输出 HTML 或其他内容之后调用。header() 函数在任何输出之前调用,或者使用 ob_start() 开启输出缓冲。<?php
ob_start();
// 你的代码
header("Location: https://www.example.com/new-page.php");
ob_end_flush();
?><?php
if (!isset($_SESSION['user_id'])) {
header("Location: https://www.example.com/login.php");
exit();
}
?>通过以上内容,你应该对 PHP 重定向有了全面的了解,并且能够解决常见的重定向问题。