[TOC]
# 請求環境
每個HTTP請求(通常由瀏覽器發起)包含有關請求的附加信息,例如標題數據,文件,變量等。基于Web的應用程序需要解析該信息,以便向請求者提供正確的響應。`Phalcon\Http\Request`封裝了請求的信息,允許您以面向對象的方式訪問它。
```php
<?php
use Phalcon\Http\Request;
// Getting a request instance
$request = new Request();
// Check whether the request was made with method POST
if ($request->isPost()) {
// Check whether the request was made with Ajax
if ($request->isAjax()) {
echo 'Request was made using POST and AJAX';
}
}
```
## 獲取值
PHP根據請求的類型自動填充超全局數組`$_GET`和`$_POST`。這些數組包含提交的表單中存在的值或通過URL發送的參數。數組中的變量永遠不會被清理,并且可能包含非法字符甚至惡意代碼,這可能導致[SQL注入](http://en.wikipedia.org/wiki/SQL_injection)或[跨站點腳本(XSS)](http://en.wikipedia.org/wiki/Cross-site_scripting)攻擊。
`Phalcon\Http\Request` 允許您訪問存儲在`$_REQUEST`,`$_GET`和`$_POST`數組中的值,并使用過濾器服務(默認為Phalcon \ Filter)清理或過濾它們。以下示例提供相同的行為:
```php
<?php
use Phalcon\Filter;
$filter = new Filter();
// Manually applying the filter
$email = $filter->sanitize($_POST['user_email'], 'email');
// Manually applying the filter to the value
$email = $filter->sanitize($request->getPost('user_email'), 'email');
// Automatically applying the filter
$email = $request->getPost('user_email', 'email');
// Setting a default value if the param is null
$email = $request->getPost('user_email', 'email', 'some@example.com');
// Setting a default value if the param is null without filtering
$email = $request->getPost('user_email', null, 'some@example.com');
```
## 訪問控制器的請求
訪問請求環境的最常見位置是控制器的操作。要從控制器訪問`Phalcon\Http\Request`對象,您需要使用控制器的 `$this->request`公共屬性:
```php
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function indexAction()
{
}
public function saveAction()
{
// Check if request has made with POST
if ($this->request->isPost()) {
// Access POST data
$customerName = $this->request->getPost('name');
$customerBorn = $this->request->getPost('born');
}
}
}
```
## 上傳文件
另一個常見任務是文件上傳。`Phalcon\Http\Request`提供了一種面向對象的方式來完成這項任務:
```php
<?php
use Phalcon\Mvc\Controller;
class PostsController extends Controller
{
public function uploadAction()
{
// Check if the user has uploaded files
if ($this->request->hasFiles()) {
$files = $this->request->getUploadedFiles();
// Print the real file names and sizes
foreach ($files as $file) {
// Print file details
echo $file->getName(), ' ', $file->getSize(), '\n';
// Move the file into the application
$file->moveTo(
'files/' . $file->getName()
);
}
}
}
}
```
`Phalcon\Http\Request::getUploadedFiles()`返回的每個對象都是`Phalcon\Http\Request\File`類的實例。使用`$_FILES` 超全局數組提供相同的行為。`Phalcon\Http\Request\File`僅封裝與請求一起上載的每個文件相關的信息。
## 使用Headers
如上所述,Headers包含有用的信息,允許我們將適當的響應發送回用戶。以下示例顯示了該信息的用法:
```php
<?php
// Get the Http-X-Requested-With header
$requestedWith = $request->getHeader('HTTP_X_REQUESTED_WITH');
if ($requestedWith === 'XMLHttpRequest') {
echo 'The request was made with Ajax';
}
// Same as above
if ($request->isAjax()) {
echo 'The request was made with Ajax';
}
// Check the request layer
if ($request->isSecure()) {
echo 'The request was made using a secure layer';
}
// Get the servers's IP address. ie. 192.168.0.100
$ipAddress = $request->getServerAddress();
// Get the client's IP address ie. 201.245.53.51
$ipAddress = $request->getClientAddress();
// Get the User Agent (HTTP_USER_AGENT)
$userAgent = $request->getUserAgent();
// Get the best acceptable content by the browser. ie text/xml
$contentType = $request->getAcceptableContent();
// Get the best charset accepted by the browser. ie. utf-8
$charset = $request->getBestCharset();
// Get the best language accepted configured in the browser. ie. en-us
$language = $request->getBestLanguage();
// Check if a header exists
if ($request->hasHeader('my-header')) {
echo "Mary had a little lamb";
}
```
## 事件
使用HTTP授權時,`Authorization`標頭具有以下格式:
```text
Authorization: <type> <credentials>
```
其中 `<type>` 是一種身份驗證類型。常見的類型是 `Basic`。其他身份驗證類型在身份驗證方案的[IANA注冊表](http://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml)和[AWS服務器的身份驗證(AWS4-HMAC-SHA256)](https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-auth-using-authorization-header.html)中進行了描述。在99.99%的用例中,身份驗證類型為:
* `AWS4-HMAC-SHA256`
* `Basic`
* `Bearer`
* `Digest`
* `HOBA`
* `Mutual`
* `Negotiate`
* `OAuth`
* `SCRAM-SHA-1`
* `SCRAM-SHA-256`
* `vapid`
您可以使用`request:beforeAuthorizationResolve`和`request:afterAuthorizationResolve` 事件在授權解析之前或之后執行其他操作。需要自定義授權解析程序。
不使用自定義授權解析程序的示例:
```php
<?php
use Phalcon\Http\Request;
$_SERVER['HTTP_AUTHORIZATION'] = 'Enigma Secret';
$request = new Request();
print_r($request->getHeaders());
```
結果:
```bash
Array
(
[Authorization] => Enigma Secret
)
Type: Enigma
Credentials: Secret
```
使用自定義授權解析程序的示例:
```php
<?php
use Phalcon\Di;
use Phalcon\Events\Event;
use Phalcon\Http\Request;
use Phalcon\Events\Manager;
class NegotiateAuthorizationListener
{
public function afterAuthorizationResolve(Event $event, Request $request, array $data)
{
if (empty($data['server']['CUSTOM_KERBEROS_AUTH'])) {
return false;
}
list($type,) = explode(' ', $data['server']['CUSTOM_KERBEROS_AUTH'], 2);
if (!$type || stripos($type, 'negotiate') !== 0) {
return false;
}
return [
'Authorization'=> $data['server']['CUSTOM_KERBEROS_AUTH'],
];
}
}
$_SERVER['CUSTOM_KERBEROS_AUTH'] = 'Negotiate a87421000492aa874209af8bc028';
$di = new Di();
$di->set('eventsManager', function () {
$manager = new Manager();
$manager->attach('request', new NegotiateAuthorizationListener());
return $manager;
});
$request = new Request();
$request->setDI($di);
print_r($request->getHeaders());
```
結果:
```bash
Array
(
[Authorization] => Negotiate a87421000492aa874209af8bc028
)
Type: Negotiate
Credentials: a87421000492aa874209af8bc028
```
- 常規
- Welcome
- 貢獻
- 生成回溯
- 測試重現
- 單元測試
- 入門
- 安裝
- Web服務器設置
- WAMP
- XAMPP
- 教程
- 基礎教程
- 教程:創建一個簡單的REST API
- 教程:V?kuró
- 提升性能
- 教程:INVO
- 開發環境
- Phalcon Compose (Docker)
- Nanobox
- Phalcon Box (Vagrant)
- 開發工具
- Phalcon開發者工具的安裝
- Phalcon開發者工具的使用
- 調試應用程序
- 核心
- MVC應用
- 微應用
- 創建命令行(CLI)應用程序
- 依賴注入與服務定位
- MVC架構
- 服務
- 使用緩存提高性能
- 讀取配置
- 上下文轉義
- 類加載器
- 使用命名空間
- 日志
- 隊列
- 數據庫
- 數據庫抽象層
- Phalcon查詢語言(PHQL)
- ODM(對象文檔映射器)
- 使用模型
- 模型行為
- ORM緩存
- 模型事件
- 模型元數據
- 模型關系
- 模型事務
- 驗證模型
- 數據庫遷移
- 分頁
- 前端
- Assets管理
- 閃存消息
- 表單
- 圖像
- 視圖助手(標簽)
- 使用視圖
- Volt:模板引擎
- 業務邏輯
- 訪問控制列表(ACL)
- 注解解析器
- 控制器
- 調度控制器
- 事件管理器
- 過濾與清理
- 路由
- 在session中存儲數據
- 生成URL和路徑
- 驗證
- HTTP
- Cookies管理
- 請求環境
- 返回響應
- 安全
- 加密/解密
- 安全
- 國際化
- 國際化
- 多語言支持