Retrieving request data using JInput

From Joomla! Documentation


Overview

The Joomla Input class (previously known as JInput class) allows you to retrieve the parameters which were sent in the HTTP request. It doesn't matter whether the parameters are HTTP GET parameters (specified in the ?param=val query part of the URL) or POST parameters (specified in the body of the HTTP request), both are accessible via the methods described here.

You can specify a filter to be applied to the parameter value, so that what you receive back is sanitised and in the form which you expect.

For example, if you expect a parameter p1 to be an integer, then you can apply an "INTEGER" filter when you get its value. Then if someone specifies ?p1=82abc5 in the URL string you will get back the value 82. (No error is raised if the value doesn't match what you expect – you just get the result of passing the value through the filter).

Using JInput

To use JInput you must first create an object of the Input class by using this code:

use Joomla\CMS\Factory;
$input = Factory::getApplication()->input;
// equivalent of the older format $input = JFactory::getApplication()->input;

then to get the value of a specific parameter use

$val = $input->get(param_name, default_value, filter);

where:

  • param_name is a string containing the name of the parameter you want to retrieve
  • default_value is the value you want returned if the parameter is not found; it may be a string, integer, array, null, etc. – whatever you want.
  • filter is a string specifying one of the filters in the list below. If you don't specify this parameter then a default of "cmd" is used.

As an example, the code below shows how to get the value of a parameter p1. The value of the parameter is passed through a "string" filter which will remove html tags and the like. If the parameter doesn't exist then the string "xxx" is returned.

use Joomla\CMS\Factory;

$app = Factory::getApplication();   // equivalent of $app = JFactory::getApplication();
$input = $app->input;
$p1 = $input->get('p1', 'xxx', 'string');

The method exists() can also be used to check if a parameter exists, but in practice this isn't often used, as using the default_value parameter usually covers adequately the case when a parameter is absent.

Available Filters

Below is a list of the available filters, together with a little explanation if appropriate, and some code which is intended to clarify what the filter is actually doing. Filters can be specified in either lower or upper case, and if 2 filters are listed on the same line below, then it indicates that they are equivalent.

Info non-talk.png
General Information

The code fragments in the following list show the implementation of the filters (assuming the value you want to retrieve is stored in $source). You do not need them to use JInput; all you need for using JInput is the code shown above.

  • "INT", "INTEGER" - returns the first integer found in the parameter value
// Only use the first integer value
preg_match('/-?[0-9]+/', (string) $source, $matches);
$result = @ (int) $matches[0];
  • "UINT" - returns an unsigned int. For example, if the parameter is specified ?p1=-2 then this filter will discard the minus sign and you will get the value 2 returned as the value of p1.
// Only use the first integer value
preg_match('/-?[0-9]+/', (string) $source, $matches);
$result = @ abs((int) $matches[0]);
  • "FLOAT", "DOUBLE" - returns the first float found
// Only use the first floating point value
preg_match('/-?[0-9]+(\.[0-9]+)?/', (string) $source, $matches);
$result = @ (float) $matches[0];
  • "BOOL", "BOOLEAN" - be careful with this! If you specify in the URL ?p1=false then the value of p1 is actually the string "false" and as this is a non-empty string (bool) p1 will return true.
$result = (bool) $source;
  • "WORD"
// Only allow characters a-z, and underscores
$result = (string) preg_replace('/[^A-Z_]/i', '', $source);
  • "ALNUM" - alphanumeric
// Allow a-z and 0-9 only
$result = (string) preg_replace('/[^A-Z0-9]/i', '', $source);
  • "CMD" - used often when obtaining the ?option=controller.task parameter in Joomla components. This is the default filter.
// Allow a-z, 0-9, underscore, dot, dash. Also remove leading dots from result. 
$result = (string) preg_replace('/[^A-Z0-9_\.-]/i', '', $source);
$result = ltrim($result, '.');
  • "BASE64" - base64 can be used to encode a URL as a string of text, which is then stored in a request parameter. For example, if a user accesses a URL which is protected then he/she may be redirected to the URL of the login page, with the original URL being base64 encoded and stored as a (return) parameter within the redirected URL. Once the user has logged in correctly the return parameter is retrieved and he/she is redirected back to the original URL accessed. (Note that you still have to decode the base64 yourself, the filter doesn't do this for you).
// Allow a-z, 0-9, slash, plus, equals.
$result = (string) preg_replace('/[^A-Z0-9\/+=]/i', '', $source);
  • "STRING"
// Converts the input to a plain text string; strips all tags / attributes.
$result = (string) $this->_remove($this->_decode((string) $source));
  • "HTML"
// Converts the input to a string; strips all HTML tags / attributes.
$result = (string) $this->_remove($this->_decode((string) $source));
  • "ARRAY"
// Attempts to convert the input to an array.
$result = (array) $source;
  • "PATH"
// Converts the input into a string and validates it as a path. (e.g. path/to/file.png or path/to/dir)
// Note: Does NOT accept absolute paths, or paths ending in a trailing slash.
// For a visual representation of the pattern matching used, see http://www.regexper.com/#^[A-Za-z0-9_-]%2B[A-Za-z0-9_\.-]*%28[\\\\\%2F][A-Za-z0-9_-]%2B[A-Za-z0-9_\.-]*%29*%24
// Will return null if the input was invalid.
$pattern = '/^[A-Za-z0-9_-]+[A-Za-z0-9_\.-]*([\\\\\/][A-Za-z0-9_-]+[A-Za-z0-9_\.-]*)*$/';
preg_match($pattern, (string) $source, $matches);
$result = @ (string) $matches[0];
  • "RAW" - be careful using this, to avoid injection attacks on your website!
// The raw input. No sanitisation provided.
$result = $source;
  • "USERNAME"
// Strips all invalid username characters.
$result = (string) preg_replace('/[\x00-\x1F\x7F<>"\'%&]/', '', $source)

Alternatively instead of adding the filter you can use the JInput type specific methods, for example:

// Instead of:
$input->get('name', '', 'STRING');
// you can use:
$input->getString('name', '');

// Instead of:
$input->get('memberId', 0, 'INT');
// you can use:
$input->getInt('memberId', 0);

Except that getArray() is different; see Getting Multiple Values below.

To retrieve an object, you can use:

$foo = $input->get(param_name, null, null);

Sample Module Code

Below is the code for a simple Joomla module which you can install and run to demonstrate retrieval of parameter values. If you are unsure about development and installing a Joomla module then following the tutorial at Creating a simple module will help.

In a folder mod_input create the following 2 files:

mod_input.xml

<?xml version="1.0" encoding="utf-8"?>
<extension type="module" version="3.1" client="site" method="upgrade">
    <name>Input demo</name>
    <version>1.0.1</version>
    <description>Code demonstrating use of Joomla Input class to obtain HTTP parameters</description>
    <files>
        <filename module="mod_input">mod_input.php</filename>
    </files>
</extension>

mod_input.php

<?php
defined('_JEXEC') or die('Restricted Access');

use Joomla\CMS\Factory;

$app = Factory::getApplication();   // equivalent of $app = JFactory::getApplication();
$input = $app->input;

if ($input->exists('p1'))
{
	$v1 = $input->get('p1', 0, "INT");  // rhs equivalent to $input->getInt('p1', 0);
	echo "<p>Int value of p1 is $v1</p>";
	$v1 = $input->get('p1', 0, "UINT"); // uint
	echo "<p>Uint value of p1 is $v1</p>";
	$v1 = $input->get('p1', 0, "string"); 
	echo "<p>String Value of p1 is $v1</p>";
}
else
{
	echo "<p>Parameter p1 not specified</p>";
}

Zip up the mod_input directory to create mod_input.zip.

Within your Joomla administrator go to Install Extensions and via the Upload Package File tab upload this zip file to install this sample module.

Make this module visible by editing it (click on it within the Modules page) then:

  1. making its status Published
  2. selecting a position on the page for it to be shown
  3. on the menu assignment tab specify the pages it should appear on

Display a web page on which this module appears. Then add the p1 parameter to the URL

  • if the URL has no existing parameters then append ?p1=123abc
  • if the URL has existing parameters then append &p1=123abc

You should see the results of retrieving the p1 parameter, and passing it through different filters. You can experiment by specifying different values for p1, applying different filters, and you can use a utility such as curl to send HTTP POST parameters to confirm it works for those as well.

Getting Multiple Values

To retrieve a number of values you can use the getArray() method:

$fooValues = $input->getArray(array('p1' => '', 'p2' => '', 'p3' => ''));

or, if you want to determine the data to get step by step:

$fooArray = array();
$fooArray['p1'] = '';
$fooArray['p2'] = '';
$fooArray['p3'] = '';
$fooValues = $input->getArray($fooArray);

The $fooValues will be an array that consists of the same keys as used in $fooArray, but with values attached.

You can also specify different filters for each of the inputs:

$fooValues = $input->getArray(array(
    'p1' => 'int',
    'p2' => 'float',
    'p3' => 'word'
));

You can also nest arrays to get more complicated hierarchies of values:

$fooValues = $input->getArray(array(
    'jform' => array(
        'title' => 'string',
        'quantity' => 'int',
        'state' => 'int'
    )
));

Getting Values from a Specific Super Global

You can retrieve values relating specifically to the PHP $_GET, $_POST and $_SERVER global variables:

$val = $input->get->get(param_name, default_value, filter);
$val = $input->post->get(param_name, default_value, filter);
$val = $input->server->get(param_name, default_value, filter);

Getting JSON string from request

NB! Available since Joomla! version 3.0.

$json = $input->json->get(param_name);

Setting Values

The functions set() and def() allow you to set input parameters and their values.

$input->set('p2', "someval");

sets the value of parameter p2 to the string "someval" (creating p2 if it doesn't already exist).

  
$input->def('p2', "someval");

creates a parameter p2 and sets its value to the string "someval", but only if p2 doesn't already exist. If p2 already exists then def('p2', "someval"); does nothing.

Retrieving File Data

The format that PHP returns file data in for arrays can at times be awkward, especially when dealing with arrays of files. JInputFiles provides a convenient interface for making life a little easier, grouping the data by file.

Suppose you have a form like:

<form action="<?php echo JRoute::_('index.php?option=com_example&task=file.submit'); ?>" enctype="multipart/form-data" method="post">
	<input type="file" name="jform1[test][]" />
	<input type="file" name="jform1[test][]" />
	<input type="submit" value="submit" />
</form>

Normally, PHP would put these in an array called $_FILES that looked like:

Array
(
    [jform1] => Array
        (
            [name] => Array
                (
                    [test] => Array
                        (
                            [0] => youtube_icon.png
                            [1] => Younger_Son_2.jpg
                        )

                )

            [type] => Array
                (
                    [test] => Array
                        (
                            [0] => image/png
                            [1] => image/jpeg
                        )

                )

            [tmp_name] => Array
                (
                    [test] => Array
                        (
                            [0] => /tmp/phpXoIpSD
                            [1] => /tmp/phpWDE7ye
                        )

                )

            [error] => Array
                (
                    [test] => Array
                        (
                            [0] => 0
                            [1] => 0
                        )

                )

            [size] => Array
                (
                    [test] => Array
                        (
                            [0] => 34409
                            [1] => 99529
                        )

                )

        )

)

JInputFiles produces a result that is cleaner and easier to work with:

$files = $input->files->get('jform1');

$files then becomes:

Array
(
    [test] => Array
        (
            [0] => Array
                (
                    [name] => youtube_icon.png
                    [type] => image/png
                    [tmp_name] => /tmp/phpXoIpSD
                    [error] => 0
                    [size] => 34409
                )

            [1] => Array
                (
                    [name] => Younger_Son_2.jpg
                    [type] => image/jpeg
                    [tmp_name] => /tmp/phpWDE7ye
                    [error] => 0
                    [size] => 99529
                )

        )

)

In this way, the data from each file element is consolidated into a single array and can be indexed in a more straightforward manner.

Restrictions and Limitations

To be able to use JInput as described here, you must be using Joomla 2.5.0 or above.

Please note there were known issues with JInput and Magic Quotes (Deprecated in PHP 5.3.0 and removed in PHP 5.4.0). For this reason all core components in Joomla 2.5.x still used JRequest. As of Joomla 3.0+ magic quotes is required to be disabled and thus this is no longer an issue.