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

如何使用PHP中的header函数设置HTTP响应头

发布时间:2023-11-03 20:57:08

在PHP中,使用header函数可以设置HTTP响应头。Header函数用于发送一个原始的HTTP头。

使用header函数设置HTTP响应头的基本语法如下:

header(string $header, bool $replace = true, int $http_response_code = null)

该函数有三个参数:

1. $header:要设置的HTTP头字符串,必须包含有效的HTTP头字段,例如"Content-Type: application/json"。

2. $replace:可选参数,默认为true。如果设置为true,将替换之前的相同类型的HTTP头。如果设置为false,则在之前的HTTP头后追加该头信息。

3. $http_response_code:可选参数,用于设置HTTP响应码。

以下是使用header函数设置HTTP响应头的一些常见用法和示例:

1. 设置Content-Type头为application/json:

header("Content-Type: application/json");

2. 设置Location头,实现重定向:

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

3. 设置Cache-Control头,控制缓存:

header("Cache-Control: no-cache, must-revalidate");

4. 设置Expires头,指定响应过期时间:

header("Expires: Wed, 21 Oct 2021 07:28:00 GMT");

5. 设置HTTP响应码为404 - Not Found:

header("HTTP/1.1 404 Not Found");

6. 设置自定义HTTP头字段:

header("X-Custom-Header: Custom Value");

需要注意的是,header函数必须在发送任何实际的输出之前调用,包括HTML标签、空格、换行等。

此外,还可以使用header_remove函数来删除之前设置的HTTP头:

header_remove("Content-Type");

上述示例将删除之前设置的Content-Type头。