PHP 中获取 HTTP 头部的全面指南22


概述

HTTP 头部是包含有关 HTTP 请求或响应的其他信息的一组键值对。它们对于 Web 开发至关重要,因为它们可以用于各种目的,例如识别请求的来源、设置 cookie、缓存响应以及提供有关响应正文的信息。

获取头部

在 PHP 中,可以使用以下方法获取 HTTP 头部:
getallheaders():返回所有 HTTP 头部的关联数组,键为头部名称,值为头部值。
apache_request_headers():仅返回 Apache Web 服务器设置的 HTTP 头部,如果使用的是其他服务器,则不建议使用此函数。
http_response_header():返回所有 HTTP 响应头部的数组。

getallheaders()


getallheaders() 函数将返回所有 HTTP 头部的关联数组,键为头部名称,值为头部值。例如:
```php

```
输出:
```
Array
(
[Host] =>
[Connection] => keep-alive
[Cache-Control] => max-age=0
[Upgrade-Insecure-Requests] => 1
[User-Agent] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36
[Accept] => text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
[Accept-Encoding] => gzip, deflate, br
[Accept-Language] => en-US,en;q=0.9
[Cookie] => PHPSESSID=a5db740bfd5dba3bcd18401adea956d3
)
```

apache_request_headers()


apache_request_headers() 函数仅返回 Apache Web 服务器设置的 HTTP 头部,如果使用的是其他服务器,则不建议使用此函数。例如:
```php

```
输出:
```
Array
(
[Host] =>
[Connection] => keep-alive
[Cache-Control] => max-age=0
[Upgrade-Insecure-Requests] => 1
[User-Agent] => Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36
[Accept] => text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
[Accept-Encoding] => gzip, deflate, br
[Accept-Language] => en-US,en;q=0.9
)
```

http_response_header()


http_response_header() 函数返回所有 HTTP 响应头部的数组。例如:
```php

```
输出:
```
HTTP/1.1 200 OK
Date: Fri, 17 Feb 2023 16:04:31 GMT
Server: Apache/2.4.46 (Ubuntu)
Content-Length: 439
Connection: keep-alive
Content-Type: text/html; charset=UTF-8
```

特定头部

你还可以使用以下函数获取特定 HTTP 头部:
get_header():获取指定名称的 HTTP 头部值。
header():设置或获取 HTTP 头部。在没有参数的情况下,它将返回当前页面中设置的所有 HTTP 头部。

get_header()


get_header() 函数获取指定名称的 HTTP 头部值。例如:
```php

```
输出:
```
text/html; charset=UTF-8
```

header()


header() 函数设置或获取 HTTP 头部。在没有参数的情况下,它将返回当前页面中设置的所有 HTTP 头部。例如:
```php

```
设置标头后,它将发送到客户端。

获取 HTTP 头部对于 Web 开发非常重要。PHP 提供了多种方法来获取头部,你可以根据自己的需要选择最合适的方法。通过理解如何获取头部,你可以更有效地控制 Web 应用程序的行为。

2024-10-24


上一篇:PHP 文件:功能、类型和用法

下一篇:PHP 字符串相等判断的进阶指南