ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 请求头 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.