PHP中的header()函数使用方法及其调用方式
在PHP中,header()函数用于发送原始的HTTP头信息。它的调用方式如下:
header(string $string, bool $replace = true, int $http_response_code = 0): void
其中,参数$string表示要发送的HTTP头信息,$replace表示是否要替换之前的头信息(默认为true),$http_response_code表示要设置的HTTP状态码(默认为0)。
下面是一些常见的使用方法和调用方式:
1. 设置Content-Type头信息:
header("Content-Type: text/html");
2. 设置重定向:
header("Location: http://www.example.com");
3. 设置HTTP状态码:
header("HTTP/1.1 404 Not Found");
4. 设置Cookie:
header("Set-Cookie: name=value; expires=Fri, 31 Dec 2022 23:59:59 GMT; path=/");
5. 设置缓存控制:
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
6. 设置下载文件头信息:
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"filename.txt\"");
7. 禁止页面被嵌入到其他网站:
header("X-Frame-Options: DENY");
8. 设置CORS头信息:
header("Access-Control-Allow-Origin: https://www.example.com");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
注意事项:
- 使用header()函数前不能有任何输出,包括空格、换行等。
- 调用header()函数后,应立即退出脚本,否则后续输出可能会影响到发送的头信息。
- 头信息中的字符编码应和脚本中的编码一致,否则可能会导致乱码。
- 某些头信息可能需要服务器的支持才能生效,如下载文件、跨域等。
总结:
header()函数可以用于发送各种HTTP头信息,包括重定向、设置状态码、设置Cookie、设置缓存控制和下载文件等。使用时需要注意调用方式和注意事项,确保头信息能够正确发送。
