Request Component


    Phalcon\Http\Request is a component that encapsulates the actual HTTP request (usually originated by a browser) and sent to our application. The object is a simple value object that is passed between the dispatcher and controller classes, wrapping the HTTP request environment. It also offers easy access to information such as header data, files, method, variables etc.

    Getting Values

    PHP automatically fills the superglobal arrays , $_POST and depending on the type of the request. These arrays contain the values present in forms submitted or the parameters sent via the URL. The variables in the arrays are never sanitized and can contain illegal characters or even malicious code, which can lead to SQL injection or attacks.

    Phalcon\Http\Request allows you to access the values stored in the , $_POST and arrays and sanitize or filter them with the filter service.

    There are 5 methods that allow you to retrieve submitted data from a request:

    • getQuery()
    • getPost()
    • getPut()
    • getServer()All (except getServer()) accept the following parameters:

    • name the name of the value to get

    • filters (array/string) the sanitizers to apply to the value
    • defaultValue returned if the element is not defined (null)
    • notAllowEmpty if set (default) and the value is empty, the defaultValue will be returned; otherwise null
    • noRecursive applies the sanitizers recursively in the value (if value is an array)
    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $request->get(
    5. $name = null, // string
    6. $filters = null, // mixed
    7. $defaultValue = null, // mixed
    8. $notAllowEmpty = false, // bool
    9. $noRecursive = false // bool
    10. ): mixed

    getServer() accepts only a name (string) variable, representing the name of the server variable that you need to retrieve.

    The superglobal contains an associative array that contains the contents of $_GET, and $_COOKIE. You can retrieve the data stored in the array by calling the get() method in the object as follows:

    ExamplesGet the userEmail field from the $_REQUEST superglobal:

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $email = $request->get('userEmail');

    Get the userEmail field from the $_REQUEST superglobal. Sanitize the value with the email sanitizer:

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $email = $request->get('userEmail', 'email', '[email protected]');

    Get the userEmail field from the $_REQUEST superglobal. Do not sanitize it. If the parameter is null, return the default value:

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $email = $request->get('userEmail', null, '');

    $_GET

    The superglobal contains an associative array that contains the variables passed to the current script via URL parameters (also known as the query string). You can retrieve the data stored in the array by calling the getQuery() method as follows:

    ExamplesGet the userEmail field from the $_GET superglobal:

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $email = $request->getQuery('userEmail');

    Get the userEmail field from the $_GET superglobal. Sanitize the value with the email sanitizer:

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $email = $request->getQuery('userEmail', 'email', '[email protected]');

    Get the userEmail field from the $_GET superglobal. Do not sanitize it. If the parameter is null, return the default value:

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $email = $request->getQuery('userEmail', null, '');

    $_POST

    The superglobal contains an associative array that contains the variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. You can retrieve the data stored in the array by calling the getPost() method as follows:

    Get the userEmail field from the $_POST superglobal. Sanitize the value with the email sanitizer:

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $email = $request->getPost('userEmail', 'email', '[email protected]');

    Get the userEmail field from the $_POST superglobal. Do not sanitize it. If the parameter is null, return the default value:

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $email = $request->getPost('userEmail', null, '');

    The request object parses the PUT stream that has been received internally. You can retrieve the data stored in the array by calling the getPut() method as follows:

    ExamplesGet the userEmail field from the PUT stream:

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $email = $request->getPut('userEmail');

    Get the userEmail field from the PUT stream. Sanitize the value with the email sanitizer:

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $email = $request->getPut('userEmail', 'email', '[email protected]');

    Get the userEmail field from the PUT stream. Do not sanitize it. If the parameter is null, return the default value:

    1. use Phalcon\Http\Request;
    2. $request = new Request();
    3. $email = $request->getPut('userEmail', null, '');

    $_SERVER

    The superglobal contains an array containing information such as headers, paths, and script locations. You can retrieve the data stored in the array by calling the method as follows:

    ExamplesGet the SERVER_NAME value from the $_SERVER superglobal:

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $name = $request->getServer('SERVER_NAME');

    Preset sanitizers

    It is relatively common that certain fields are using the same name throughout your application. A field posted from a form in your application can have the same name and function with another form in a different area. Examples of this behavior could be id fields, name etc.

    To make the sanitization process easier, when retrieving such fields, offers a method to define those sanitizing filters based on HTTP methods when setting up the object.

    1. <?php
    2. use Phalcon\Di;
    3. use Phalcon\Filter;
    4. use Phalcon\Http\Request;
    5. $container = new Di();
    6. $container->set(
    7. 'request',
    8. function () {
    9. $request = new Request();
    10. $request
    11. ->setParameterFilters('id', Filter::FILTER_ABSINT, ['post'])
    12. ->setParameterFilters('name', ['trim', 'string'], ['post'])
    13. ;
    14. return $request;
    15. }
    16. );

    The above will automatically sanitize any parameter that is POSTed from a form that has a name id or name with their respective filters. Sanitization takes place when calling the following methods (one per HTTP method)

    • getFilteredPost()
    • getFilteredPut()
    • getFilteredQuery()These methods accept the same parameters as the getPost(), getPut() and getQuery() but without the $filter parameter.

    Controllers

    If you use the container, the Phalcon\Http\Request is already registered for you. The most common place to access the request environment is in an action of a controller. To access the object from a controller you will need to use the $this->request public property of the controller:

    The Phalcon\Http\Request component contains a number of methods that help you check the current operation. For instance if you want to check if a particular request was made using AJAX, you can do so by using the isAjax() method. All the methods are prefixed with is.

    • isAjax(): Checks whether request has been made using AJAX
    • isConnect(): Checks whether HTTP method is CONNECT
    • isDelete(): Checks whether HTTP method is DELETE
    • isGet(): Checks whether HTTP method is GET
    • isHead(): Checks whether HTTP method is HEAD
    • isMethod(): Check if HTTP method match any of the passed methods
    • isOptions(): Checks whether HTTP method is OPTIONS
    • isPatch(): Checks whether HTTP method is PATCH
    • isPost(): Checks whether HTTP method is POST
    • isPurge(): Checks whether HTTP method is PURGE (Squid and Varnish support)
    • isPut(): Checks whether HTTP method is PUT
    • isSecure(): Checks whether request has been made using any secure layer
    • isSoap(): Checks whether request has been made using SOAP
    • isTrace(): Checks whether HTTP method is TRACE
    • isValidHttpMethod(): Checks if a method is a valid HTTP method

    Checking existence

    There are a number of methods available that allow you to check the existence of elements in the request. These methods are prefixed with has. Depending on the method used, you can check if an element exists in the $_REQUEST, $_GET, $_POST, $_SERVER, $_FILES, PUT cache and the request headers.

    • has(): Checks whether the $_REQUEST superglobal has a certain element
    • hasFiles(): Checks whether the request has any uploaded files
    • hasHeader(): Checks whether the headers have a certain element
    • hasPost(): Checks whether $_POST superglobal has a certain element
    • hasPut(): Checks whether the PUT data has a certain element
    • hasQuery(): Checks whether $_GET superglobal has a certain element
    • hasServer(): Checks whether $_SERVER superglobal has a certain element

    Request information

    The object offers methods that provide additional information regarding the request.

    Authentication

    • getBasicAuth(): Gets auth info accepted by the browser/client
    • getDigestAuth(): Gets auth info accepted by the browser/client
    • getClientAddress(): Gets most possible client IPv4 Address
    • getClientCharsets(): Gets a charsets array and their quality accepted by the browser/client
    • getUserAgent(): Gets HTTP user agent used to made the request
    • getHTTPReferer(): Gets web page that refers active request

    Content

    • getAcceptableContent(): Gets an array with mime/types and their quality accepted by the browser/client
    • getBestAccept(): Gets best mime/type accepted by the browser/client
    • getContentType(): Gets content type which request has been made
    • getJsonRawBody(): Gets decoded JSON HTTP raw request body
    • getRawBody(): Gets HTTP raw request body

    i18n

    • getBestCharset(): Gets best charset accepted by the browser/client
    • getBestLanguage(): Gets best language accepted by the browser/client
    • getLanguages(): Gets languages array and their quality accepted by the browser/client
    • getPort(): Gets information about the port on which the request is made
    • getServerAddress(): Gets active server address IP
    • getServerName(): Gets active server name
    • getScheme(): Gets HTTP schema (http/https)
    • getURI(): Gets HTTP URI which request has been made
    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. if ($request->isAjax()) {
    5. echo 'The request was made with Ajax';
    6. }
    7. // Check the request layer
    8. if ($request->isSecure()) {
    9. echo 'The request was made using a secure layer';
    10. }
    11. // Get the servers's IP address. ie. 192.168.0.100
    12. $ipAddress = $request->getServerAddress();
    13. // Get the client's IP address ie. 201.245.53.51
    14. $ipAddress = $request->getClientAddress();
    15. // Get the User Agent (HTTP_USER_AGENT)
    16. $userAgent = $request->getUserAgent();
    17. // Get the best acceptable content by the browser. ie text/xml
    18. $contentType = $request->getAcceptableContent();
    19. // Get the best charset accepted by the browser. ie. utf-8
    20. $charset = $request->getBestCharset();
    21. // Get the best language accepted configured in the browser. ie. en-us
    22. $language = $request->getBestLanguage();

    Method

    getMethod() returns the HTTP method which request has been made. If the X-HTTP-Method-Override header is set, and if the method is a POST, then it is used to determine the “real” intended HTTP method. The _method request parameter can also be used to determine the HTTP method, setHttpMethodParameterOverride(true) has been called. The method always returns an uppercase string.

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request();
    4. $_SERVER['REQUEST_METHOD'] = 'POST';
    5. echo $request->getMethod();
    6. // GET
    7. /**
    8. *
    9. * header('X-HTTP-Method-Override: GET');
    10. */
    11. $_SERVER['REQUEST_METHOD'] = 'POST';
    12. $request->setHttpMethodParameterOverride(true);
    13. echo $request->getMethod();
    14. // GET
    15. $_SERVER['REQUEST_METHOD'] = 'POST';
    16. $_REQUEST['_method'] = 'GET';
    17. $request->setHttpMethodParameterOverride(true);
    18. echo $request->getMethod();

    Dependency Injection

    Request headers contain useful information, allowing you to take necessary steps to send the proper response back to the user. The exposes the getHeader() and getHeaders() methods.

    1. <?php
    2. use Phalcon\Http\Request;
    3. $request = new Request;
    4. $_SERVER["HTTP_HOST"] = "example.com";
    5. $request->getHttpHost(); // example.com
    6. $_SERVER["HTTP_HOST"] = "example.com:8080";
    7. $request->getHttpHost(); // example.com:8080
    8. $request->setStrictHostCheck(true);
    9. $_SERVER["HTTP_HOST"] = "ex=am~ple.com";
    10. $request->getHttpHost(); // UnexpectedValueException
    11. $_SERVER["HTTP_HOST"] = "ExAmPlE.com";
    12. $request->getHttpHost(); // example.com

    The getHttpHost() method will return the host name used by the request. The method will try to find host name in following order:

    • $_SERVER["HTTP_HOST"]
    • $_SERVER["SERVER_NAME"]
    • $_SERVER["SERVER_ADDR"]Optionally getHttpHost() validates and performs a strict check on the host name. To achieve that you can use the setStrictHostCheck() method.

    Uploaded Files

    Another common task is file uploading. offers an object-oriented way work with files. For the whole upload process to work, you will need to make the necessary changes to your php.ini (see php-uploads).

    1. <?php
    2. use Phalcon\Http\Request;
    3. use Phalcon\Mvc\Controller;
    4. /**
    5. * Class PostsController
    6. *
    7. * @property Request $request
    8. */
    9. class PostsController extends Controller
    10. {
    11. public function uploadAction()
    12. {
    13. // Check if the user has uploaded files
    14. if ($this->request->hasFiles()) {
    15. $files = $this->request->getUploadedFiles();
    16. // Print the real file names and sizes
    17. foreach ($files as $file) {
    18. // Print file details
    19. echo $file->getName(), ' ', $file->getSize(), '\n';
    20. // Move the file into the application
    21. $file->moveTo(
    22. 'files/' . $file->getName()
    23. );
    24. }
    25. }
    26. }
    27. }

    Each object returned by Phalcon\Http\Request::getUploadedFiles() is an instance of the which implements the Phalcon\Http\Request\FileInterface class. Using the $_FILES superglobal array offers the same behavior. encapsulates only the information related to each file uploaded with the request.

    The getUploadedFiles() accepts two parameters.

    • $onlySuccessful: Contains only successful uploads
    • $namedKeys: Returns the array with named keys obtained by the upload processThe method returns an array of Phalcon\Http\Request\File objects. Each object offers the following properties and methods, allowing you to work with uploaded files:

    • getError() (string) - Returns any error that happened with this file

    • getExtension() (string) - Returns the extension of the file
    • getKey() (string) - Returns the internal key of the file
    • getName() (string) -Returns the real name of the uploaded file
    • getRealType() (string) - Return the real mime type of the upload file using finfo
    • getSize() (int) - Returns the file size of the uploaded file
    • getTempName() (string) - Returns the temporary name of the uploaded file
    • getType() (string) - Returns the mime type reported by the browser. This mime type is not completely secure, use getRealType() instead
    • isUploadedFile() (bool) - Checks whether the file has been uploaded via POST.
    • moveTo(string $destination) (bool) - Moves the temporary file to a destination within the application

    Dependency Injection

    The Phalcon\Http\Request object implements the interface. As a result, the DI container is available and can be retrieved using the getDI() method. A container can also be set using the setDI() method.

    Events

    The object implements the Phalcon\Events\EventsAware interfaces. As a result getEventsManager() and setEventsManager() are available for you to use.

    When using HTTP authorization, the Authorization header has the following format:

    1. Authorization: <type> <credentials>

    where <type> is an authentication type. A common type is Basic. Additional authentication types are described in and Authentication for AWS servers (AWS4-HMAC-SHA256). In most use cases the authentication type is:

    • AWS4-HMAC-SHA256
    • Basic
    • Bearer
    • Digest
    • HOBA
    • Mutual
    • Negotiate
    • OAuth
    • SCRAM-SHA-1
    • SCRAM-SHA-256
    • vapidYou can use the request:beforeAuthorizationResolve and request:afterAuthorizationResolve events to perform additional operations before or after the authorization resolves.

    The request:beforeAuthorizationResolve receives the SERVER array with the key server as the second parameter of the event.

    The request:afterAuthorizationResolve receives the SERVER array with the key server as well as the headers with the hey headers.

    A custom authorization resolver is required.

    Example without using custom authorization resolver:

    1. <?php
    2. use Phalcon\Http\Request;
    3. $_SERVER['HTTP_AUTHORIZATION'] = 'Enigma Secret';
    4. $request = new Request();
    5. print_r($request->getHeaders());

    Result:

    1. Array
    2. (
    3. [Authorization] => Enigma Secret
    4. )
    5. Type: Enigma
    6. Credentials: Secret

    Result:

    1. Array
    2. (
    3. [Authorization] => Negotiate a87421000492aa874209af8bc028
    4. )
    5. Type: Negotiate