欢迎访问宙启技术站
智能推送

使用PHP中的`header()`函数进行页面重定向的方法。

发布时间:2023-10-12 07:20:50

在PHP中,可以使用header()函数进行页面重定向。header()函数用于发送原始的HTTP报头,包括重定向。要进行页面重定向,需要使用header()函数设置Location头部,指定要重定向到的URL。以下是使用header()函数进行页面重定向的方法:

1. 重定向到其他页面:

header("Location: http://www.example.com");
exit();

上述代码将页面重定向到http://www.example.com地址,并使用exit()函数确保后续的代码不会被执行。

2. 重定向到相对路径:

header("Location: /new-page.php");
exit();

这将页面重定向到位于根目录下的new-page.php文件。

3. 使用HTTP状态码进行重定向:

header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.example.com");
exit();

在上述代码中,使用header()函数设置HTTP/1.1 301 Moved Permanently状态码进行永久重定向。

4. 延迟重定向:

header("Refresh: 5; url=http://www.example.com");
echo "将在5秒后重定向到http://www.example.com";

这将在5秒后自动重定向到http://www.example.com。使用Refresh头部可以实现延迟重定向。

5. 设置cookie:

header("Location: http://www.example.com");
header("Set-Cookie: cookie_name=cookie_value; expires=Sat, 31-Dec-2022 23:59:59 GMT; path=/");
exit();

在上述代码中,使用Set-Cookie头部设置cookie,在重定向的同时,设置了名为cookie_name的cookie。

6. 添加其他HTTP头部:

header("Location: http://www.example.com");
header("X-Custom-Header: custom_value");
exit();

可以使用header()函数设置其他自定义的HTTP头部。

请注意,header()函数必须在发送任何输出之前调用,否则会导致"headers already sent"错误。