多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[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 ```