How To Get and Sanitize Form Data In Joomla
Forms are extensively used in Joomla, both in administration and front-end. You can get data after form submission using JInput. It also provides various ways to filter and sanitise your input data.
Step 1
To use JInput, first create the object by using this code:
$jinput = JFactory::getApplication()->input;
Step 2
Then, to get a value from JInput, use:
$var_name = $jinput->get('variable_name', 'default_value', 'filter');
variable_name is the name given in field declaration in the XML file. The filter defaults to cmd.
Available Filters
You can use any of the following filters:
-
INT: Only use the first integer value
-
UINT: Only use the first integer value, converts integer value to absolute
-
FLOAT: Only use the first floating point value
-
BOOLEAN:
-
WORD: Only allow characters a-z, and underscores
-
ALNUM: Allow a-z and 0-9 only
-
CMD: Allow a-z, 0-9, underscore, dot, dash. Also remove leading dots from result
-
BASE64: Allow a-z, 0-9, slash, plus, equals
-
STRING: Converts the input to a plain text string; strips all tags / attributes
-
HTML: Converts the input to a string; strips all HTML tags / attributes
-
ARRAY: Attempts to convert the input to an array
-
PATH: Converts the input into a string and validates it as a path
-
RAW: The raw input. No sanitation provided.
-
USERNAME: Strips all invalid username characters
How to Get Joomla Component, View and Item ID
You can get the name of the Joomla component and item id of the current page in the similar way.
$input = JFactory::getApplication()->input;
$option = $input->get('option');
$view = $input->get('view');
$id = $input->getInt('id');
$catid = $params->get('catid');
For example, you can check whether the current page is from content component.
if ($option === 'com_content')
{
switch ($view)
{
case 'category' :
$id = $input->getInt('id');
break;
case 'categories' :
$id = $input->getInt('id');
break;
case 'article' :
$id = $input->getInt('catid');
}
}