Difference between revisions of "Retrieving request data using JInput"

From Joomla! Documentation

m (Added categorisation.)
(Add array syntax)
 
(26 intermediate revisions by 12 users not shown)
Line 1: Line 1:
{{JVer|11.1}} {{JVer|1.7}}
+
{{version|2.5,3.x|platform=11.1,12.1}}
  
==Requirements==
+
== Overview ==
To be able to use JInput as described here, you must be using Joomla 1.7.1 or above.
+
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 <tt>?param=val</tt> query part of the URL) or POST parameters (specified in the body of the HTTP request), both are accessible via the methods described here.
  
==Starting JInput==
+
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.
To use JInput you must first create the object by using this code:
 
  
<source lang="php">$jinput = JFactory::getApplication()->input;</source>
+
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 <tt>?p1=82abc5</tt> in the URL string you will get back the value <tt>82</tt>. (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).
  
===Getting values===
+
==Using JInput==
To get a value from JInput you can use:
+
To use JInput you must first create an object of the Input class by using this code:
  
<source lang="php">$foo = $jinput->get('varname', 'default_value', 'filter');</source>
+
<source lang="php">
 +
use Joomla\CMS\Factory;
 +
$input = Factory::getApplication()->input;
 +
// equivalent of the older format $input = JFactory::getApplication()->input;
 +
</source>
 +
 
 +
then to get the value of a specific parameter use
 +
 
 +
<source lang="php">
 +
$val = $input->get(param_name, default_value, filter);
 +
</source>
 +
 
 +
where:
 +
* <tt>param_name</tt> is a string containing the name of the parameter you want to retrieve
 +
* <tt>default_value</tt> is the value you want returned if the parameter is not found; it may be a string, integer, array, null, etc. – whatever you want.
 +
* <tt>filter</tt> 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.
 +
 
 +
<source lang="php">
 +
use Joomla\CMS\Factory;
 +
 
 +
$app = Factory::getApplication();  // equivalent of $app = JFactory::getApplication();
 +
$input = $app->input;
 +
$p1 = $input->get('p1', 'xxx', 'string');
 +
</source>
 +
 
 +
'''JInput returns an array of filtered entries if the user input is an array. Calling the above example with ?p1[]=xxx will return $p1 as array with one element 'xxx' filter as string.'''
 +
 
 +
The method <tt>exists()</tt> can also be used to check if a parameter exists, but in practice this isn't often used, as using the <tt>default_value</tt> 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.
 +
 
 +
{{notice|The code fragments in the following list show the ''implementation'' of the filters (assuming the value you want to retrieve is stored in <code>$source</code>). 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
 +
 
 +
<source lang="php">
 +
// Only use the first integer value
 +
preg_match('/-?[0-9]+/', (string) $source, $matches);
 +
$result = @ (int) $matches[0];
 +
</source>
 +
 
 +
* "UINT" - returns an unsigned int. For example, if the parameter is specified <tt>?p1=-2</tt> then this filter will discard the minus sign and you will get the value <tt>2</tt> returned as the value of <tt>p1</tt>.
 +
 
 +
<source lang="php">
 +
// Only use the first integer value
 +
preg_match('/-?[0-9]+/', (string) $source, $matches);
 +
$result = @ abs((int) $matches[0]);
 +
</source>
 +
 
 +
* "FLOAT", "DOUBLE" - returns the first float found
 +
 
 +
<source lang="php">
 +
// Only use the first floating point value
 +
preg_match('/-?[0-9]+(\.[0-9]+)?/', (string) $source, $matches);
 +
$result = @ (float) $matches[0];
 +
</source>
 +
 
 +
* "BOOL", "BOOLEAN" - be careful with this! If you specify in the URL <tt>?p1=false</tt> then the value of <tt>p1</tt> is actually the string <tt>"false"</tt> and as this is a non-empty string <tt>(bool) p1</tt> will return <tt>true</tt>.
 +
 
 +
<source lang="php">
 +
$result = (bool) $source;
 +
</source>
 +
 
 +
* "WORD"
 +
 
 +
<source lang="php">
 +
// Only allow characters a-z, and underscores
 +
$result = (string) preg_replace('/[^A-Z_]/i', '', $source);
 +
</source>
 +
 
 +
* "ALNUM" - alphanumeric
 +
 
 +
<source lang="php">
 +
// Allow a-z and 0-9 only
 +
$result = (string) preg_replace('/[^A-Z0-9]/i', '', $source);
 +
</source>
 +
 
 +
* "CMD" - used often when obtaining the <tt>?option=controller.task</tt> parameter in Joomla components. This is the default filter.
 +
 
 +
<source lang="php">
 +
// 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, '.');
 +
</source>
 +
 
 +
* "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).
 +
 
 +
<source lang="php">
 +
// Allow a-z, 0-9, slash, plus, equals.
 +
$result = (string) preg_replace('/[^A-Z0-9\/+=]/i', '', $source);
 +
</source>
 +
 
 +
* "STRING"
 +
<source lang="php">
 +
// Converts the input to a plain text string; strips all tags / attributes.
 +
$result = (string) $this->_remove($this->_decode((string) $source));
 +
</source>
 +
 
 +
* "HTML"
 +
<source lang="php">
 +
// Converts the input to a string; strips all HTML tags / attributes.
 +
$result = (string) $this->_remove($this->_decode((string) $source));
 +
</source>
 +
 
 +
* "ARRAY"
 +
<source lang="php">
 +
// Attempts to convert the input to an array.
 +
$result = (array) $source;
 +
</source>
 +
 
 +
* "PATH"
 +
<source lang="php">
 +
// 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];
 +
</source>
 +
 
 +
* "RAW" - be careful using this, to avoid injection attacks on your website!
 +
 
 +
<source lang="php">
 +
// The raw input. No sanitisation provided.
 +
$result = $source;
 +
</source>
 +
 
 +
* "USERNAME"
 +
<source lang="php">
 +
// Strips all invalid username characters.
 +
$result = (string) preg_replace('/[\x00-\x1F\x7F<>"\'%&]/', '', $source)
 +
</source>
 +
 
 +
Alternatively instead of adding the filter you can use the JInput type specific methods, for example:
 +
 
 +
<source lang="php">
 +
// 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);
 +
</source>
 +
 
 +
Except that <tt>getArray()</tt> is different; see [[Retrieving request data using JInput#Getting Multiple Values|Getting Multiple Values]] below.
 +
 
 +
To retrieve an object, you can use:
 +
<source lang="php">
 +
$foo = $input->get(param_name, null, null);
 +
</source>
 +
 
 +
== 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 [[S:MyLanguage/J3.x:Creating a simple module/Introduction| Creating a simple module ]] will help.
 +
 
 +
In a folder mod_input create the following 2 files:
 +
 
 +
<tt>mod_input.xml</tt>
 +
<source lang="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>
 +
</source>
 +
 
 +
<tt>mod_input.php</tt>
 +
<source lang="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>";
 +
}
 +
</source>
 +
 
 +
Zip up the mod_input directory to create <tt>mod_input.zip</tt>.
 +
 
 +
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:
 +
# making its status Published
 +
# selecting a position on the page for it to be shown
 +
# on the menu assignment tab specify the pages it should appear on
 +
 
 +
Display a web page on which this module appears. Then add the <tt>p1</tt> parameter to the URL
 +
* if the URL has no existing parameters then append <tt>?p1=123abc</tt>
 +
* if the URL has existing parameters then append <tt>&p1=123abc</tt>
 +
 
 +
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 [https://curl.haxx.se/ 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 <code>getArray()</code> method:
 +
 
 +
<source lang="php">
 +
$fooValues = $input->getArray(array('p1' => '', 'p2' => '', 'p3' => ''));
 +
</source>
 +
 
 +
or, if you want to determine the data to get step by step:
 +
 
 +
<source lang="php">
 +
$fooArray = array();
 +
$fooArray['p1'] = '';
 +
$fooArray['p2'] = '';
 +
$fooArray['p3'] = '';
 +
$fooValues = $input->getArray($fooArray);
 +
</source>
 +
 
 +
The <code>$fooValues</code> will be an array that consists of the same keys as used in <code>$fooArray</code>, but with values attached.
 +
 
 +
You can also specify different filters for each of the inputs:
 +
 
 +
<source lang="php>
 +
$fooValues = $input->getArray(array(
 +
    'p1' => 'int',
 +
    'p2' => 'float',
 +
    'p3' => 'word'
 +
));
 +
</source>
 +
 
 +
You can also nest arrays to get more complicated hierarchies of values:
 +
 
 +
<source lang="php">
 +
$fooValues = $input->getArray(array(
 +
    'jform' => array(
 +
        'title' => 'string',
 +
        'quantity' => 'int',
 +
        'state' => 'int'
 +
    )
 +
));
 +
</source>
 +
 
 +
== Getting Values from a Specific Super Global ==
 +
 
 +
You can retrieve values relating specifically to the PHP <tt>$_GET</tt>, <tt>$_POST</tt> and <tt>$_SERVER</tt> global variables:
 +
 
 +
<source lang="php">
 +
$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);
 +
</source>
  
The filter defaults to cmd
+
== Getting JSON string from request ==
 +
'''NB!''' Available since Joomla! version 3.0.
  
Available filters are:
+
<source lang="php">$json = $input->json->get(param_name);</source>
  
*INT
+
== Setting Values ==
*INTEGER
 
*UINT
 
*FLOAT
 
*DOUBLE
 
*BOOL
 
*BOOLEAN
 
*WORD
 
*ALNUM
 
*CMD
 
*BASE64
 
*STRING
 
*HTML
 
*ARRAY
 
*PATH
 
*USERNAME
 
  
To retrieve a number of values you can use the getArray() method like:
+
The functions <tt>set()</tt> and <tt>def()</tt> allow you to set input parameters and their values.
  
 
<source lang="php">
 
<source lang="php">
$fooarray = array();
+
$input->set('p2', "someval");  
$fooarray[] = 'var1';
+
</source>
$fooarray[] = 'var2';
+
sets the value of parameter p2 to the string "someval" (creating p2 if it doesn't already exist).
$fooarray[] = 'var3';
+
 
$foovalues = $jinput->getArray($fooarray);</source>
+
<source lang="php"> 
 +
$input->def('p2', "someval");  
 +
</source> 
 +
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 <tt>def('p2', "someval");</tt> 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:
 +
<source lang="html4strict">
 +
<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>
 +
</source>
 +
 
 +
Normally, PHP would put these in an array called <code>$_FILES</code> that looked like:
 +
<pre>
 +
Array
 +
(
 +
    [jform1] => Array
 +
        (
 +
            [name] => Array
 +
                (
 +
                    [test] => Array
 +
                        (
 +
                            [0] => youtube_icon.png
 +
                            [1] => Younger_Son_2.jpg
 +
                        )
 +
 
 +
                )
  
The $foovalues will be an array that consists of the same keys as used in $fooarray.
+
            [type] => Array
 +
                (
 +
                    [test] => Array
 +
                        (
 +
                            [0] => image/png
 +
                            [1] => image/jpeg
 +
                        )
  
To retrieve values from a specific super global you can use:
+
                )
  
<source lang="php">$foo = $jinput->get->get('varname', 'default_value', 'filter');</source>
+
            [tmp_name] => Array
<source lang="php">$foo = $jinput->post->get('varname', 'default_value', 'filter');</source>
+
                (
<source lang="php">$foo = $jinput->server->get('varname', 'default_value', 'filter');</source>
+
                    [test] => Array
 +
                        (
 +
                            [0] => /tmp/phpXoIpSD
 +
                            [1] => /tmp/phpWDE7ye
 +
                        )
  
To retrieve an object you can use:
+
                )
<source lang="php">$foo = $jinput->get('varname', null, null);</source>
 
  
===Setting values===
+
            [error] => Array
To set a value via JInput you can use:
+
                (
 +
                    [test] => Array
 +
                        (
 +
                            [0] => 0
 +
                            [1] => 0
 +
                        )
  
<source lang="php">$jinput->set('varname', $foo);</source>
+
                )
  
 +
            [size] => Array
 +
                (
 +
                    [test] => Array
 +
                        (
 +
                            [0] => 34409
 +
                            [1] => 99529
 +
                        )
  
This is based on an email discussion: [https://groups.google.com/d/msg/joomla-dev-framework/LbALkK1ifMo/5waSiIlb21gJ Framework List 23 July 2011]
+
                )
  
The idea behind JInput is to abstract out the input source to allow code to be reused in different applications and in different contexts.  What I mean by this is that you could have a controller that grabs data from an input source.  Instead of always getting it from the request (i.e. get and post variables), you get it from JInput.  So say for instance you have a MVC triad in your component that is meant to get data from the browser as a client (a typical web application).  Now suppose you want to reuse that same code but interface with it using JSON.  Instead of rewriting your triad, you just extend JInput and have it grab it data from a parsed json object and perform any translation that you need to perform.
+
        )
  
The plan is to have JApplication instantiate JInput in its constructor.  Then in your code you get the input object from the application and get your input from there.  It will be a public property in Japplication so that it can be swapped out of that is appropriate.
+
)
 +
</pre>
 +
 
 +
JInputFiles produces a result that is cleaner and easier to work with:
 +
<source lang="php">
 +
$files = $input->files->get('jform1');
 +
</source>
  
We get the added benefit that we get rid of the static JRequest which makes a whole bunch the code a whole lot easier to test because you can inject mock inputs directly instead of trying to fudge with hackish dependencies.
+
<code>$files</code> then becomes:
  
The end result will be that your code will get the input object from the application (we will probably add something to JController at some point to make it more convenient to use there as well).
+
<pre>
 +
Array
 +
(
 +
    [test] => Array
 +
        (
 +
            [0] => Array
 +
                (
 +
                    [name] => youtube_icon.png
 +
                    [type] => image/png
 +
                    [tmp_name] => /tmp/phpXoIpSD
 +
                    [error] => 0
 +
                    [size] => 34409
 +
                )
  
Once you have your JInput object, you use it fairly in a fairly similar manner to how JRequest is used:
+
            [1] => Array
$input->get('varname', 'default_value', 'filter');
+
                (
 +
                    [name] => Younger_Son_2.jpg
 +
                    [type] => image/jpeg
 +
                    [tmp_name] => /tmp/phpWDE7ye
 +
                    [error] => 0
 +
                    [size] => 99529
 +
                )
  
Where filter is a filter that is supported by JFilterInput.  JInput::clean proxies to JFilter.  We'll have to tweak JFilter a little bit so that it is more extensible.  It defaults to cmd so that developers have to be intentional about things if they want to have more lenient filtering.
+
        )
  
There is also a getArray method that allows you to specify an array of key and filter pairs so that you can get a whole array of filtered input.
+
)
 +
</pre>
  
If you want to get data from a specific super global array, you can do $input->get->get(...) or $input->post->get(...).
+
In this way, the data from each file element is consolidated into a single array and can be indexed in a more straightforward manner.
  
So that's the basic idea.  Feel free to post more questions if you have any.
+
== Restrictions and Limitations ==
 +
To be able to use JInput as described here, you must be using Joomla 2.5.0 or above.
  
We'll be adding input as a public property to JApplication in the near future. It might be an idea if the CMS folks so chose to release a 1.7.1 that included this so developers can use it now. Otherwise, at this point in time, it is best to still use JRequest.
+
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.
  
 +
<noinclude>
 +
[[Category:Tutorials]]
 
[[Category:Development]]
 
[[Category:Development]]
 +
</noinclude>

Latest revision as of 03:22, 13 January 2020


Overview[edit]

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[edit]

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');

JInput returns an array of filtered entries if the user input is an array. Calling the above example with ?p1[]=xxx will return $p1 as array with one element 'xxx' filter as 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[edit]

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[edit]

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[edit]

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[edit]

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[edit]

NB! Available since Joomla! version 3.0.

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

Setting Values[edit]

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[edit]

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[edit]

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.