PHP函数:header()用于发送HTTP头
发布时间:2023-09-21 12:32:27
header()函数用于发送HTTP头。在PHP中,我们可以使用它来设置响应的一些重要信息,如状态码、内容类型、缓存控制、重定向等。
下面是header()函数的语法:
header(string $header, bool $replace = true, int $http_response_code = null)
- $header:要发送的HTTP头的内容,格式为"Header-name: value"。
- $replace:可选参数,用于指定是否替换之前的相同类型的头,默认为true,表示替换。
- $http_response_code:可选参数,用于设置HTTP响应状态码。
以下是一些常见的使用示例:
1. 设置响应状态码:
header("HTTP/1.1 200 OK");
2. 设置内容类型为HTML:
header("Content-type: text/html");
3. 设置缓存控制:
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
4. 重定向到另一个页面:
header("Location: http://www.example.com");
5. 设置下载文件的头:
header("Content-Disposition: attachment; filename=\"example.pdf\"");
需要注意的是,必须在发送任何其他内容之前调用header()函数,否则会引发"headers already sent"错误。此外,如果要使用header()函数设置响应状态码,必须在设置之前没有输出任何内容。
总结:header()函数是PHP中用于发送HTTP头的函数,可以设置响应状态码、内容类型、缓存控制和重定向等重要信息。通过合理使用header()函数,我们可以控制响应的行为和格式,从而实现更灵活的Web应用程序设计。
