如何使用header函数在PHP中设置响应头?
发布时间:2023-06-30 09:58:03
在PHP中,可以使用header()函数来设置HTTP响应头。该函数用于发送原始的HTTP头信息给客户端,可以用来控制页面的缓存、跳转、设置Cookie等。
以下是如何使用header()函数设置响应头的一些常见示例:
1. 设置页面编码:
header('Content-Type: text/html; charset=utf-8');
2. 设置页面跳转:
header('Location: http://www.example.com');
注意:在调用header('Location: ...')之前,应确保没有输出任何内容到浏览器。否则,会导致报错。
3. 设置缓存控制:
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
header('Pragma: no-cache');
4. 设置下载文件:
$file = 'path/to/file.pdf';
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
这个示例先设置了响应的Content-Type为application/pdf,然后通过Content-Disposition告诉浏览器以附件方式打开文件,最后使用readfile函数将文件内容输出到浏览器。
5. 设置Cookie:
$name = 'username'; $value = 'John Doe'; $expire = time() + 3600; // 设置cookie的过期时间为1小时后 $path = '/'; $domain = 'example.com'; $secure = true; // 仅在使用HTTPS时发送cookie $httpOnly = true; // 设置为true时,cookie无法通过JavaScript访问 setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly);
以上只是一些常见的使用示例,header()函数还可以用来设置其他HTTP头。需要注意的是,所有的header()函数调用都必须在页面输出之前进行,否则会报错。另外,一旦使用header()函数发送了响应头,后续的任何输出都将被视为响应体的一部分。
