# 请求头
Every HTTP request has headers. These are metadata that describe the HTTP request but are not visible in the request’s body. Slim’s PSR-7 Request object provides several methods to inspect its headers.
> 每个HTTP请求都有标头。这些元数据描述了HTTP请求,但在请求体中不可见。Slim的PSR-7请求对象提供了几个方法来检查它的头文件。
## 获取所有请求头 getHeaders
You can fetch all HTTP request headers as an associative array with the PSR-7 Request object’s`getHeaders()`method. The resultant associative array’s keys are the header names and its values are themselves a numeric array of string values for their respective header name.
> 您可以通过PSR-7请求对象的`getHeaders()`方法获取所有HTTP请求头信息。由此产生的关联数组的键是标题名,其值本身是各自标题名的字符串值的数字数组。
~~~php
$headers = $request->getHeaders();
foreach ($headers as $name => $values) {
echo $name . ": " . implode(", ", $values);
}
~~~
Figure 5: Fetch and iterate all HTTP request headers as an associative array.
## 获取一个请求头 getHeaderLine
You can get a single header’s value(s) with the PSR-7 Request object’s`getHeader($name)`method. This returns an array of values for the given header name. Remember,*a single HTTP header may have more than one value!*
> 您可以使用PSR-7请求对象的`getHeader($name)`方法获得单个头文件的值。这将返回给定标题名称的值数组。记住,*一个HTTP报头可能有多个值!*
~~~php
$headerValueArray = $request->getHeader('Accept');
~~~
Figure 6: Get values for a specific HTTP header.
You may also fetch a comma-separated string with all values for a given header with the PSR-7 Request object’s`getHeaderLine($name)`method. Unlike the`getHeader($name)`method, this method returns a comma-separated string.
> 您还可以使用PSR-7请求对象的`getHeaderLine($name)`方法获取一个以逗号分隔的字符串,其中包含给定标题的所有值。与`getHeader($name)`方法不同,该方法返回一个逗号分隔的字符串。
~~~php
$headerValueString = $request->getHeaderLine('Accept');
~~~
Figure 7: Get single header's values as comma-separated string.
## Detect Header 检测请求头 hasHeader
You can test for the presence of a header with the PSR-7 Request object’s`hasHeader($name)`method.
> 您可以使用PSR-7请求对象的`hasHeader($name)`方法测试报头是否存在。
~~~php
if ($request->hasHeader('Accept')) {
// Do something
}
~~~
Figure 8: Detect presence of a specific HTTP request header.
- 开始
- 安装
- 升级指南
- Web服务器
- 概念
- 生命周期
- PSR 7
- 中间件
- 依赖容器
- 实例 及通知和警告处理
- Request
- 请求方法
- 请求头信息
- 请求主体
- 上传的文件
- 请求帮助
- 路由对象
- Response
- 响应状态
- 响应标头
- 响应体
- 返回JSON
- 视图模板
- 路由
- 创建路由
- 路由回调
- 路由策略
- 路线占位符
- 路由名
- 路由组
- 路由中间件
- 路由表达式缓存
- 容器识别解析
- 封装中间件
- 路由的中间件
- 错误处理中间件
- 方法重写的中间件
- 输出缓冲中间件
- 内容长度中间件
- 扩展功能
- 以 / 结尾的路由模式
- 获取当前路由
- 设置CORS
- 使用POST表单上传文件
- 第三方组件
- slim-session
- auth
- slim-api-skeleton
- dir