请求环境
最后更新于:2022-04-02 05:15:33
[TOC]
# 请求环境
每个HTTP请求(通常由浏览器发起)包含有关请求的附加信息,例如标题数据,文件,变量等。基于Web的应用程序需要解析该信息,以便向请求者提供正确的响应。`Phalcon\Http\Request`封装了请求的信息,允许您以面向对象的方式访问它。
```php
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
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
request->isPost()) {
// Access POST data
$customerName = $this->request->getPost('name');
$customerBorn = $this->request->getPost('born');
}
}
}
```
## 上传文件
另一个常见任务是文件上传。`Phalcon\Http\Request`提供了一种面向对象的方式来完成这项任务:
```php
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
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:
```
其中 `` 是一种身份验证类型。常见的类型是 `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
getHeaders());
```
结果:
```bash
Array
(
[Authorization] => Enigma Secret
)
Type: Enigma
Credentials: Secret
```
使用自定义授权解析程序的示例:
```php
$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
```
';