Retrieving and Filtering GET and POST requests with JRequest::getVar
From Joomla! Documentation
Revision as of 08:54, 29 February 2012 by Jumpy972
When writing any web application, it is crucial that you filter input data before using it. Joomla! provides a set of filtering libraries to help you accomplish this.
To retrieve GET/POST request data, Joomla! uses the getVar method of the JRequest class (JRequest::getVar()).
If you have a form variable named 'address', you would want to use this code to get it:
$address = JRequest::getVar('address');
Unless other parameters are set, all HTML and trailing whitespace will be filtered out.
The DEFAULT Parameter
If you want to specify a default value in the event that 'address' is not in the request or is unset, use this code:
$address = JRequest::getVar('address', 'Address is empty'); echo $address; // Address is empty
The SOURCE Parameter
Frequently, you will expect your variable to be found in a specific portion of the HTTP request (POST, GET, etc...). If this is the case, you should specify which portion; this will slightly increase your extension's security. If you expect 'address' to only be in POST, use this code to enforce that:
$address = JRequest::getVar('address', 'default value goes here', 'post');
The VARIABLE TYPE Parameter
The fourth parameter of getVar() can be used to specify certain filters to force validation of specific value types for the variable.
$address = JRequest::getVar('address', 'default value goes here', 'post','variable type');
Here is a list of types you can validate:
The FILTER MASK Parameter
Finally, there are some mask constants you can pass in as the fifth parameter that allow you to bypass portions of the filtering:
$address = JRequest::getVar('address', 'default value goes here', 'post','validation type',mask type);
- JREQUEST_NOTRIM - prevents trimming of whitespace
- JREQUEST_ALLOWRAW - bypasses filtering
- JREQUEST_ALLOWHTML - allows most HTML. If this is not passed in, HTML is stripped out by default.
Note. These are static variables not strings. Do not use quotes around them
To receive a whole array filtered. If you would want to get the POST data, you can use this.
JRequest::get( 'post' )
This returns the standard POST array. You can use it on a template page if needed, or in the models section if convenient. It returns the most recent POST. Methods of this object were not found in the Framework section where one would expect to find them.
Why not just use the Superglobals? If you are familiar with PHP already you may be wondering, why not just use $_GET / $_POST / $_REQUEST? To make Joomla more secure, all global variables should be read through this function. It removes the possibility for code injection and/or SQL injection. You can also define a default value (as you can see in line 6). Copied and changed from Creating a simple component - Part 1.