Spec-Zone.ru › Phalcon 3

Окружение запроса

Каждый HTTP-запрос (обычно исходящий от браузера) содержит дополнительную информацию, такую как данные заголовков, файлы, переменные и т. д. Веб-приложение должно разобрать эту информацию, чтобы правильно ответить запрашивающему. Phalcon\Http\Request инкапсулирует информацию о запросе, позволяя получить к ней доступ объектно-ориентированным способом.

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 или атакам типа Cross Site Scripting (XSS).

Phalcon\Http\Request позволяет получить доступ к значениям, хранящимся в массивах $_REQUEST, $_GET и $_POST, и очистить или отфильтровать их с помощью сервиса «filter» (по умолчанию Phalcon\Filter). Следующие примеры демонстрируют одинаковое поведение:

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", "[email protected]");

// Setting a default value if the param is null without filtering
$email = $request->getPost("user_email", null, "[email protected]");

Доступ к запросу из контроллеров

Самое распространенное место для доступа к окружению запроса — действие контроллера. Для доступа к объекту Phalcon\Http\Request из контроллера необходимо использовать общедоступное свойство контроллера $this->request.

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 предлагает объектно-ориентированный способ решения этой задачи:

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 инкапсулирует только информацию, связанную с каждым загруженным файлом в запросе.

Работа с заголовками

Как упоминалось выше, заголовки запроса содержат полезную информацию, которая позволяет отправлять правильный ответ пользователю. Следующие примеры демонстрируют использование этой информации:

// 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();

© 2011–2017 Phalcon Framework Team
Licensed under the Creative Commons Attribution License 3.0.
https://docs.phalconphp.com/en/latest/reference/request.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API