# 請求頭
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