logo

深入理解 PHP 的 header 函数

深入理解 PHP 的 header 函数

PHP 中 header 函数发送 HTTP 标信息我们服务器进行 HTTP 操作设置状态设置我们 PHP 的 header 函数

我们 header 函数

php header(string $header, bool $replace = true, int $http_response_code = null): void 



- $header 参数发送 HTTP 标信息字符串
- $replace 参数是否设置类型信息默认 true表示
- $http_response_code 参数设置状态

 header 函数

1. 设置状态

php header('HTTP/1.1 200 OK'); 



2. 执行页面

php header('Location: http://www.example.com'); 



3. 设置

php header('Cache-Control: no-cache, must-revalidate');
   header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); 



4. 发文件下载

php header('Content-Disposition: attachment; filename="example.pdf"');
   header('Content-Type: application/pdf');
   header('Content-Length: ' . filesize('example.pdf'));
   readfile('example.pdf'); 



5. 防 XSS 攻

php header('Content-Type: text/html; charset=UTF-8');
   header('X-XSS-Protection: 1; mode=block'); 



需要注意以下

- 在 header 函数不能输出 "headers already sent" 错
- 如果使用 header 函数设置信息需要 $replace 参数设置 false发送
- header 函数发送输出 HTML 标

header 函数发送信息不能发送 Cookie 或 Set-Cookie 标我们可以使用 setcookie 函数

我们 PHP 的 header 函数通过使用 header 函数我们可以 HTTP 操作 header 函数 PHP 开

 

 

原创不易,如果觉得文章对你有帮助,欢迎点赞、评论。文章有疏漏之处,欢迎批评指正。

欢迎转载,转载请注明原文链接:https://blog.beibeiling.com/66618103/1.html

标签: header php 基础语法