使用PHPheader()函数发送HTTP头信息。
PHP的header()函数用于向客户端发送HTTP头信息。它可以用来设置响应头,重定向页面,设置Cookie等。
语法:
header(string $header[, bool $replace[, int $http_response_code]]);
参数:
$header:要发送的HTTP头信息,格式为"Header: value"。
$replace:是否替换之前的相同类型的头信息,默认为true,即替换。
$http_response_code:HTTP响应码,使用该参数可以设置HTTP响应码。
下面是一些使用header()函数的示例:
1. 设置响应类型为JSON:
header('Content-Type: application/json');
2. 设置重定向:
header('Location: http://www.example.com');
3. 设置Cookie:
header('Set-Cookie: user_id=12345; Expires=Wed, 21 Oct 2021 07:28:00 GMT; Path=/');
4. 设置HTTP响应码:
header('HTTP/1.1 404 Not Found');
5. 禁用浏览器缓存:
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
6. 设置下载文件:
header('Content-Disposition: attachment; filename="file.txt"');
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
更复杂的情况下,可以利用PHP的数组将多个头信息一次性发送:
$headers = array(
'Content-Type: application/pdf',
'Content-Disposition: attachment; filename="file.pdf"',
'Content-Length: ' . filesize($file)
);
header($headers);
需要注意的是,header()函数必须在输出任何内容之前调用,否则会出现“header already sent”错误。
