php实现重定向
PHP 重定向的实现方法
在 PHP 中,可以通过 header() 函数实现页面的重定向。以下是几种常见的重定向方式:
使用 header() 函数进行重定向
header("Location: https://example.com");
exit;
确保在调用 header() 函数之前没有输出任何内容(包括空格或 HTML),否则会导致错误。exit 或 die 用于终止脚本执行,防止后续代码继续运行。
延迟重定向

header("Refresh: 5; url=https://example.com");
echo "You will be redirected in 5 seconds.";
Refresh 头部可以指定延迟时间(秒)和目标 URL,适用于需要显示提示信息的场景。
301 永久重定向

header("HTTP/1.1 301 Moved Permanently");
header("Location: https://example.com/new-page");
exit;
301 重定向对 SEO 更友好,表示资源已永久移动到新地址。
302 临时重定向
header("HTTP/1.1 302 Found");
header("Location: https://example.com/temporary");
exit;
302 重定向表示资源临时移动到新地址,浏览器会继续请求原地址。
注意事项
- 确保
header()调用前无输出,否则会触发Cannot modify header information错误。 - 重定向后使用
exit或die终止脚本,避免后续代码执行。 - 对于现代 PHP 版本,推荐使用绝对 URL(包含
http://或https://)。






