使用header函数在PHP中设置HTTP响应头。
发布时间:2023-07-03 21:01:39
在PHP中,可以使用header函数来设置HTTP响应头。通过设置不同的HTTP响应头,可以控制浏览器和服务器之间的通信。
header函数的使用方式为:
header(string $header, bool $replace = true, int $http_response_code = null)
参数说明:
1. $header:要设置的HTTP头字段,以字符串形式传入。必须以"Header-Name: Value"的格式提供。
2. $replace:一个可选的布尔值参数,用于指定是否替换之前发送的相同头字段。如果设置为true,则替换;如果设置为false,则在之前的响应头字段之后追加。默认为true。
3. $http_response_code:一个可选的整型参数,用于指定服务器返回的响应状态码。
下面是一些常用的HTTP响应头的设置示例:
1. 设置Content-Type头字段,告诉浏览器返回的内容的类型:
header("Content-Type: text/html");
2. 设置Location头字段,用于重定向到其他页面:
header("Location: http://www.example.com");
3. 设置Cache-Control头字段,用于定义缓存策略:
header("Cache-Control: no-cache, no-store, must-revalidate");
4. 设置Expires头字段,用于指定资源的过期时间:
$expireTime = time() + 3600; // 设置为当前时间加上一小时
header("Expires: " . gmdate("D, d M Y H:i:s", $expireTime) . " GMT");
5. 设置Content-Disposition头字段,用于指定浏览器显示下载内容的方式:
header("Content-Disposition: attachment; filename=\"filename.pdf\"");
需要注意的是,header函数必须在发送其他内容之前调用,并且只能调用一次。如果在调用header函数之前已经输出了内容,例如使用echo输出了内容,则无法再设置HTTP响应头。
最后,当需要发送自定义HTTP响应码时,可以通过header函数的第三个参数进行设置。例如:
header("HTTP/1.1 404 Not Found");
