
作者:CPP手艺人 来源: CPP手艺人 日期:2026-12-01 20:13:14
在PHP中,种用header()函数是种用(yong)一个非常重要的工具,它主要用于发送原始的(de)种(zhong)用HTTP报头,这个函数必须在输出(chu)任何实际的种用HTML或PHP代码之前调用,否则会产生错误,种(zhong)用以下是种用PHP header()函数的7种主要用法:
1、设置Content-Type头部


Content-Type头部用于告诉浏览器你(ni)正在发(fa)送什么类型的种用数(shu)据,如果你正在发送HTML,你应该设置Content-Type为text/html,你可以使用header()函数来设置这个头部。

header('Content-Type: text/html');2、设置字符集
字符集头部用于告诉浏览器你正在发送的数据的字符编码,如果你(ni)正在发(fa)送UTF-8编码的数(shu)据,你应该设置字符集头部为UTF-8,你可以使用header()函数来设置这个头部。
header('Content-Type: text/html; charset=utf-8');3、重定向
header()函数也可以用来执行HTTP重定向,你可以使(shi)用header()函数将用户从一个页面重定(ding)向到另一个页面(mian)。
header('Location: http://www.example.com');4、设置Cookie
setcookie('username', 'John Doe', time() + (86400 * 30), "/"); // 86400 = 1 day5、设置过期时间
你可以使用header()函数来设置一个Cookie的过期时间,你可以使(shi)用header()函数(shu)来设置一个名为"username"的Cookie,值为"John Doe",并在30天后过期。
setcookie('username', 'John Doe', time() + (86400 * 30), "/", "", false); // 86400 = 1 day, last parameter is to set the cookie as a session cookie, not a persistent one.6、删除Cookie
你可以使用header()函数来删除一个Cookie,你可以使用header()函数来删除一个名为"username"的Cookie。
setcookie('username', '', time() 3600); // time() 3600 = 1 hour ago7、退出当前脚本并继续执行后续代码
在某些情况下,你可能希望停止当前的PHP脚本,并继续执行后续的代码,你可以使用header()函数来实现这个目标,你可以(yi)使用header()函数(shu)来停止当前的PHP脚本,并继续执行后续的HTML代码。
exit(); // This will stop the current PHP script and continue with the rest of the HTML code.
以上就是PHP header()函数的7种主要用法,希望这些信息对你有所帮助。
相关问题(ti)与解答
1、Q: 我可以(yi)在header()函数之后输出HTML代码吗?A: 不可以,你(ni)必须在输出任何实际的HTML或PHP代码之(zhi)前调用header()函数,否则会产生错误。
3、Q: 我可以使用header()函数来设置一个Cookie的值吗?A: 可以,你可以使用(yong)header()函数来设置一个Cookie的值,你(ni)需要使用setcookie()函数来实际设置Cookie。
4、Q: 我可以使用header()函数来删除一个(ge)Cookie吗?A: 可以,你可以(yi)使用header()函数来删除一个Cookie,你需要使用setcookie()函数来实(shi)际删除Cookie。