IncomingRequest Class

The IncomingRequest class provides an object-oriented representation of an HTTP request from a client, like a browser.It extends from, and has access to all the methods of the Request and Messageclasses, in addition to the methods listed below.

Accessing the Request

An instance of the request class already populated for you if the current class is a descendant ofCodeIgniter\Controller and can be accessed as a class property:

  1. <?php namespace App\Controllers;
  2.  
  3. use CodeIgniter\Controller;
  4.  
  5. class UserController extends Controller
  6. {
  7. public function index()
  8. {
  9. if ($this->request->isAJAX())
  10. {
  11. . . .
  12. }
  13. }
  14. }

If you are not within a controller, but still need access to the application’s Request object, you canget a copy of it through the Services class:

  1. $request = \Config\Services::request();

It’s preferable, though, to pass the request in as a dependency if the class is anything other thanthe controller, where you can save it as a class property:

  1. <?php
  2. use CodeIgniter\HTTP\RequestInterface;
  3.  
  4. class SomeClass
  5. {
  6. protected $request;
  7.  
  8. public function __construct(RequestInterface $request)
  9. {
  10. $this->request = $request;
  11. }
  12. }
  13.  
  14. $someClass = new SomeClass(\Config\Services::request());

Determining Request Type

A request could be of several types, including an AJAX request or a request from the command line. This canbe checked with the isAJAX() and isCLI() methods:

  1. // Check for AJAX request.
  2. if ($request->isAJAX())
  3. {
  4. . . .
  5. }
  6.  
  7. // Check for CLI Request
  8. if ($request->isCLI())
  9. {
  10. . . .
  11. }

Note

The isAJAX() method depends on the X-Requested-With header, which in some cases is not sent by default in XHR requests via JavaScript (i.e. fetch). See the AJAX Requests section on how to avoid this problem.

You can check the HTTP method that this request represents with the method() method:

  1. // Returns 'post'
  2. $method = $request->getMethod();

By default, the method is returned as a lower-case string (i.e. ‘get’, ‘post’, etc). You can get anuppercase version by passing in true as the only parameter:

  1. // Returns 'GET'
  2. $method = $request->getMethod(true);

You can also check if the request was made through and HTTPS connection with the isSecure() method:

  1. if (! $request->isSecure())
  2. {
  3. force_https();
  4. }

Retrieving Input

You can retrieve input from $_SERVER, $_GET, $_POST, $_ENV, and $_SESSION through the Request object.The data is not automatically filtered and returns the raw input data as passed in the request. The mainadvantages to using these methods instead of accessing them directly ($_POST[‘something’]), is that theywill return null if the item doesn’t exist, and you can have the data filtered. This lets you convenientlyuse data without having to test whether an item exists first. In other words, normally you might do somethinglike this:

  1. $something = isset($_POST['foo']) ? $_POST['foo'] : NULL;

With CodeIgniter’s built in methods you can simply do this:

  1. $something = $request->getVar('foo');

The getVar() method will pull from $_REQUEST, so will return any data from $_GET, $POST, or $_COOKIE. While thisis convenient, you will often need to use a more specific method, like:

  • $request->getGet()
  • $request->getPost()
  • $request->getServer()
  • $request->getCookie()

In addition, there are a few utility methods for retrieving information from either $_GET or $_POST, whilemaintaining the ability to control the order you look for it:

  • $request->getPostGet() - checks $_POST first, then $_GET
  • $request->getGetPost() - checks $_GET first, then $_POST

Getting JSON data

You can grab the contents of php://input as a JSON stream with getJSON().

Note

This has no way of checking if the incoming data is valid JSON or not, you should only use thismethod if you know that you’re expecting JSON.

  1. $json = $request->getJSON();

By default, this will return any objects in the JSON data as objects. If you want that converted to associativearrays, pass in true as the first parameter.

The second and third parameters match up to the depth and options arguments of thejson_decode PHP function.

Retrieving Raw data (PUT, PATCH, DELETE)

Finally, you can grab the contents of php://input as a raw stream with getRawInput():

  1. $data = $request->getRawInput();

This will retrieve data and convert it to an array. Like this:

  1. var_dump($request->getRawInput());
  2.  
  3. [
  4. 'Param1' => 'Value1',
  5. 'Param2' => 'Value2'
  6. ]

Filtering Input Data

To maintain security of your application, you will want to filter all input as you access it. You canpass the type of filter to use as the last parameter of any of these methods. The native filter_var()function is used for the filtering. Head over to the PHP manual for a list of validfilter types.

Filtering a POST variable would look like this:

  1. $email = $request->getVar('email', FILTER_SANITIZE_EMAIL);

All of the methods mentioned above support the filter type passed in as the last parameter, with theexception of getJSON().

Retrieving Headers

You can get access to any header that was sent with the request with the getHeaders() method, which returnsan array of all headers, with the key as the name of the header, and the value is an instance ofCodeIgniter\HTTP\Header:

  1. var_dump($request->getHeaders());
  2.  
  3. [
  4. 'Host' => CodeIgniter\HTTP\Header,
  5. 'Cache-Control' => CodeIgniter\HTTP\Header,
  6. 'Accept' => CodeIgniter\HTTP\Header,
  7. ]

If you only need a single header, you can pass the name into the getHeader() method. This will grab thespecified header object in a case-insensitive manner if it exists. If not, then it will return null:

  1. // these are all equivalent
  2. $host = $request->getHeader('host');
  3. $host = $request->getHeader('Host');
  4. $host = $request->getHeader('HOST');

You can always use hasHeader() to see if the header existed in this request:

  1. if ($request->hasHeader('DNT'))
  2. {
  3. // Don't track something...
  4. }

If you need the value of header as a string with all values on one line, you can use the getHeaderLine() method:

  1. // Accept-Encoding: gzip, deflate, sdch
  2. echo 'Accept-Encoding: '.$request->getHeaderLine('accept-encoding');

If you need the entire header, with the name and values in a single string, simply cast the header as a string:

  1. echo (string)$header;

The Request URL

You can retrieve a URI object that represents the current URI for this request through the$request->uri property. You can cast this object as a string to get a full URL for the current request:

  1. $uri = (string)$request->uri;

The object gives you full abilities to grab any part of the request on it’s own:

  1. $uri = $request->uri;
  2.  
  3. echo $uri->getScheme(); // http
  4. echo $uri->getAuthority(); // snoopy:password@example.com:88
  5. echo $uri->getUserInfo(); // snoopy:password
  6. echo $uri->getHost(); // example.com
  7. echo $uri->getPort(); // 88
  8. echo $uri->getPath(); // /path/to/page
  9. echo $uri->getQuery(); // foo=bar&bar=baz
  10. echo $uri->getSegments(); // ['path', 'to', 'page']
  11. echo $uri->getSegment(1); // 'path'
  12. echo $uri->getTotalSegments(); // 3

Uploaded Files

Information about all uploaded files can be retrieved through $request->getFiles(), which returns aFileCollection instance. This helps to ease the pain of working with uploaded files,and uses best practices to minimize any security risks.

  1. $files = $request->getFiles();
  2.  
  3. // Grab the file by name given in HTML form
  4. if ($files->hasFile('uploadedFile')
  5. {
  6. $file = $files->getFile('uploadedfile');
  7.  
  8. // Generate a new secure name
  9. $name = $file->getRandomName();
  10.  
  11. // Move the file to it's new home
  12. $file->move('/path/to/dir', $name);
  13.  
  14. echo $file->getSize('mb'); // 1.23
  15. echo $file->getExtension(); // jpg
  16. echo $file->getType(); // image/jpg
  17. }

You can retrieve a single file uploaded on its own, based on the filename given in the HTML file input:

  1. $file = $request->getFile('uploadedfile');

You can retrieve an array of same-named files uploaded as part of amulti-file upload, based on the filename given in the HTML file input:

  1. $files = $request->getFileMultiple('uploadedfile');

Content Negotiation

You can easily negotiate content types with the request through the negotiate() method:

  1. $language = $request->negotiate('language', ['en-US', 'en-GB', 'fr', 'es-mx']);
  2. $imageType = $request->negotiate('media', ['image/png', 'image/jpg']);
  3. $charset = $request->negotiate('charset', ['UTF-8', 'UTF-16']);
  4. $contentType = $request->negotiate('media', ['text/html', 'text/xml']);
  5. $encoding = $request->negotiate('encoding', ['gzip', 'compress']);

See the Content Negotiation page for more details.

Class Reference

Note

In addition to the methods listed here, this class inherits the methods from theRequest Class and the Message Class.

The methods provided by the parent classes that are available are:

  • CodeIgniter\HTTP\Request::getIPAddress()
  • CodeIgniter\HTTP\Request::validIP()
  • CodeIgniter\HTTP\Request::getMethod()
  • CodeIgniter\HTTP\Request::getServer()
  • CodeIgniter\HTTP\Message::getBody()
  • CodeIgniter\HTTP\Message::setBody()
  • CodeIgniter\HTTP\Message::populateHeaders()
  • CodeIgniter\HTTP\Message::headers()
  • CodeIgniter\HTTP\Message::header()
  • CodeIgniter\HTTP\Message::headerLine()
  • CodeIgniter\HTTP\Message::setHeader()
  • CodeIgniter\HTTP\Message::removeHeader()
  • CodeIgniter\HTTP\Message::appendHeader()
  • CodeIgniter\HTTP\Message::protocolVersion()
  • CodeIgniter\HTTP\Message::setProtocolVersion()
  • CodeIgniter\HTTP\Message::negotiateMedia()
  • CodeIgniter\HTTP\Message::negotiateCharset()
  • CodeIgniter\HTTP\Message::negotiateEncoding()
  • CodeIgniter\HTTP\Message::negotiateLanguage()
  • CodeIgniter\HTTP\Message::negotiateLanguage()
  • CodeIgniter\HTTP\IncomingRequest
    • isCLI()

Returns:True if the request was initiated from the command line, otherwise false.Return type:bool

  • isAJAX()

Returns:True if the request is an AJAX request, otherwise false.Return type:bool

  • isSecure()

Returns:True if the request is an HTTPS request, otherwise false.Return type:bool

  • getVar([$index = null[, $filter = null[, $flags = null]]])

Parameters:

  1. - **$index** (_string_) The name of the variable/key to look for.
  2. - **$filter** (_int_) The type of filter to apply. A list of filters can be found [here](http://php.net/manual/en/filter.filters.php).
  3. - **$flags** (_int_) Flags to apply. A list of flags can be found [here](http://php.net/manual/en/filter.filters.flags.php).Returns:

$_REQUEST if no parameters supplied, otherwise the REQUEST value if found, or null if notReturn type:mixed|null

The first parameter will contain the name of the REQUEST item you are looking for:

  1. $request->getVar('some_data');

The method returns null if the item you are attempting to retrievedoes not exist.

The second optional parameter lets you run the data through the PHP’sfilters. Pass in the desired filter type as the second parameter:

  1. $request->getVar('some_data', FILTER_SANITIZE_STRING);

To return an array of all POST items call without any parameters.

To return all POST items and pass them through the filter, set thefirst parameter to null while setting the second parameter to the filteryou want to use:

  1. $request->getVar(null, FILTER_SANITIZE_STRING); // returns all POST items with string sanitation

To return an array of multiple POST parameters, pass all the required keys as an array:

  1. $request->getVar(['field1', 'field2']);

Same rule applied here, to retrieve the parameters with filtering, set the second parameter tothe filter type to apply:

  1. $request->getVar(['field1', 'field2'], FILTER_SANITIZE_STRING);
  • getGet([$index = null[, $filter = null[, $flags = null]]])

Parameters:

  1. - **$index** (_string_) The name of the variable/key to look for.
  2. - **$filter** (_int_) The type of filter to apply. A list of filters can be found [here](http://php.net/manual/en/filter.filters.php).
  3. - **$flags** (_int_) Flags to apply. A list of flags can be found [here](http://php.net/manual/en/filter.filters.flags.php).Returns:

$_GET if no parameters supplied, otherwise the GET value if found, or null if notReturn type:mixed|null

This method is identical to getVar(), only it fetches GET data.

  • getPost([$index = null[, $filter = null[, $flags = null]]])

Parameters:

  1. - **$index** (_string_) The name of the variable/key to look for.
  2. - **$filter** (_int_) The type of filter to apply. A list of filters can be found [here](http://php.net/manual/en/filter.filters.php).
  3. - **$flags** (_int_) Flags to apply. A list of flags can be found [here](http://php.net/manual/en/filter.filters.flags.php).Returns:

$_POST if no parameters supplied, otherwise the POST value if found, or null if notReturn type:

mixed|null

This method is identical to getVar(), only it fetches POST data.

  • getPostGet([$index = null[, $filter = null[, $flags = null]]])

Parameters:

  1. - **$index** (_string_) The name of the variable/key to look for.
  2. - **$filter** (_int_) The type of filter to apply. A list of filters can be found [here](http://php.net/manual/en/filter.filters.php).
  3. - **$flags** (_int_) Flags to apply. A list of flags can be found [here](http://php.net/manual/en/filter.filters.flags.php).Returns:

$_POST if no parameters supplied, otherwise the POST value if found, or null if notReturn type:mixed|null

This method works pretty much the same way as getPost() and getGet(), only combined.It will search through both POST and GET streams for data, looking first in POST, andthen in GET:

  1. $request->getPostGet('field1');
  • getGetPost([$index = null[, $filter = null[, $flags = null]]])

Parameters:

  1. - **$index** (_string_) The name of the variable/key to look for.
  2. - **$filter** (_int_) The type of filter to apply. A list of filters can be found [here](http://php.net/manual/en/filter.filters.php).
  3. - **$flags** (_int_) Flags to apply. A list of flags can be found [here](http://php.net/manual/en/filter.filters.flags.php).Returns:

$_POST if no parameters supplied, otherwise the POST value if found, or null if notReturn type:mixed|null

This method works pretty much the same way as getPost() and getGet(), only combined.It will search through both POST and GET streams for data, looking first in GET, andthen in POST:

  1. $request->getGetPost('field1');
  • getCookie([$index = null[, $filter = null[, $flags = null]]])

Noindex:Parameters:

  1. - **$index** (_mixed_) COOKIE name
  2. - **$filter** (_int_) The type of filter to apply. A list of filters can be found [here](http://php.net/manual/en/filter.filters.php).
  3. - **$flags** (_int_) Flags to apply. A list of flags can be found [here](http://php.net/manual/en/filter.filters.flags.php).Returns:

$_COOKIE if no parameters supplied, otherwise the COOKIE value if found or null if notReturn type:mixed

This method is identical to getPost() and getGet(), only it fetches cookie data:

  1. $request->getCookie('some_cookie');
  2. $request->getCookie('some_cookie', FILTER_SANITIZE_STRING); // with filter

To return an array of multiple cookie values, pass all the required keys as an array:

  1. $request->getCookie(['some_cookie', 'some_cookie2']);

Note

Unlike the Cookie Helperfunction get_cookie(), this method does NOT prependyour configured $config['cookie_prefix'] value.

  • getServer([$index = null[, $filter = null[, $flags = null]]])

Parameters:

  1. - **$index** (_mixed_) Value name
  2. - **$filter** (_int_) The type of filter to apply. A list of filters can be found [here](http://php.net/manual/en/filter.filters.php).
  3. - **$flags** (_int_) Flags to apply. A list of flags can be found [here](http://php.net/manual/en/filter.filters.flags.php).Returns:

$_SERVER item value if found, NULL if notReturn type:mixed

This method is identical to the getPost(), getGet() and getCookie()methods, only it fetches getServer data ($_SERVER):

  1. $request->getServer('some_data');

To return an array of multiple $_SERVER values, pass all the required keysas an array.

  1. $request->getServer(['SERVER_PROTOCOL', 'REQUEST_URI']);
  • getUserAgent([$filter = null])

Parameters:

  1. - **$filter** (_int_) The type of filter to apply. A list of filters can be found [here](http://php.net/manual/en/filter.filters.php).Returns:

The User Agent string, as found in the SERVER data, or null if not found.Return type:mixed

This method returns the User Agent string from the SERVER data:

  1. $request->getUserAgent();