PHP中的header()函数如何设置HTTP头部信息
PHP中的header()函数用于设置HTTP头部信息,可以控制浏览器如何解析服务器返回的内容。
使用header()函数设置HTTP头部信息,需要遵循一定的语法规则。下面是使用header()函数设置常见HTTP头部信息的示例:
1. 设置响应状态码:可以使用http_response_code()函数来设置响应的状态码,然后使用header()函数设置其他与状态码相关的头部信息。示例代码如下:
http_response_code(200);
header('Content-Type: text/html; charset=utf-8');
2. 设置重定向:
- 使用header()函数设置Location头部信息来实现重定向。
- 设置状态码为302(暂时重定向)或301(永久重定向)。
- 设置Location头部信息为目标URL。示例代码如下:
http_response_code(302);
header('Location: http://www.example.com');
3. 设置缓存:
- 使用header()函数设置Expires头部信息来设置资源的过期时间。
- 使用header()函数设置Cache-Control头部信息来设置缓存策略。示例代码如下:
$expire_time = 60 * 60 * 24 * 365; // 一年
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expire_time) . ' GMT');
header('Cache-Control: max-age=' . $expire_time);
4. 设置跨域资源共享(CORS):
- 使用header()函数设置Access-Control-Allow-Origin头部信息来允许指定来源的跨域请求。
- 使用header()函数设置Access-Control-Allow-Methods头部信息来允许指定的HTTP方法。
- 使用header()函数设置Access-Control-Allow-Headers头部信息来允许指定的请求头部信息。示例代码如下:
header('Access-Control-Allow-Origin: http://www.example.com');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type');
5. 设置文件下载:
- 使用header()函数设置Content-Disposition头部信息为attachment,用于告诉浏览器下载文件。
- 使用header()函数设置Content-Type头部信息为文件的MIME类型。示例代码如下:
header('Content-Disposition: attachment; filename="example.pdf"');
header('Content-Type: application/pdf');
需要注意的是,header()函数必须在所有实际输出之前调用,包括以下内容之前:输出HTML标签、空行、BOM(字节顺序标记)、session_start()函数、setcookie()函数。如果在输出内容之后调用header()函数,将会导致“header already sent”错误。
另外,为避免一些不可预测的错误, 在设置完所有的HTTP头部信息之后加上exit()语句,以确保脚本直接退出。示例代码如下:
http_response_code(200);
header('Content-Type: text/html; charset=utf-8');
exit();
总之,通过合理使用header()函数,可以实现对HTTP头部信息的灵活控制,有效地与浏览器交互。
