OK, so let us look at what options are available. The examples below are using JInput and have been tested in Joomla 3.3.
I am POSTing the following data at Joomla:
stuff[abc]=1
stuff[def]=75
stuff[123]=<script src="http://imanaughtysite.com/muahahaha.js"/>
I want to get a clean array of integers, so the expected result is:
$expectedResult = array(
'abc' => 1,
'def' => 75,
'123' => 0,
);
Option 1 - JInput::get() with ARRAY filter
$a1 = $app->input->get('stuff', array(), 'ARRAY');
Result:
array (size=3)
'abc' => string '1' (length=1)
'def' => string '75' (length=2)
123 => string '<script src="http://imanaughtysite.com/muahahaha.js"/>' (length=54)
BAD IDEA - as you can see, we are getting our data, but it not filtered / cleaned at all!
Option 2 - JInput::getArray() on post
$a2 = $app->input->post->getArray();
Result:
array (size=1)
'stuff' =>
array (size=3)
'abc' => string '1' (length=1)
'def' => string '75' (length=2)
123 => string '' (length=0)
Now we have the whole POST array, cleaned. But it is more information that we wanted and it is still not an array of integers.
Option 3 - JInput::getArray() specifying expected parameters and their respective filter:
$a3 = $app->input->getArray(array(
'stuff' => array(
'abc' => 'INT',
'def' => 'INT',
'123' => 'INT'
)
));
Result:
array (size=1)
'stuff' =>
array (size=3)
'abc' => int 1
'def' => int 75
123 => int 0
This is actually the first version that provides what we need. We can individually specify the filter and get the result. stuff
needs to be extracted from the resulting array and with a PHP function like array_values
we can also extract just the values, resetting the keys.
Option 4 - Improving JInput::getArray()
While Option 3 might work well, there are some issues:
- What if we do not know in advance the name of the fields?
- What if I have like 100+ fields - I don't want to write each of them
To solve this issues, we need to do it in more steps:
// Get the data unfiltered
$unfilteredData = $app->input->get('stuff', array(), 'ARRAY');
// Pre-filling all parameters with the INT filter.
$a4 = $app->input->getArray(array(
'stuff' => array_fill_keys(array_flip($unfilteredData), 'INT')
));
Result is:
array (size=1)
'stuff' =>
array (size=4)
'abc' => int 1
'def' => int 75
123 => int 0
Possible security issue if you need the keys: we are filtering the values, but not the keys!
Some simple processing:
$finalArray = array_values($a4['stuff']);
array (size=4)
0 => int 1
1 => int 75
2 => int 0
ANSWER IS HERE: -> Complete code to get an array with n-parameters as integers from a POST request (ideally fit this into a method):
// Get the data unfiltered
$unfilteredData = $app->input->get('stuff', array(), 'ARRAY');
// Check to see if array is empty.
if (! empty($unfilteredData))
{
$a4 = $app->input->getArray(array(
'stuff' => array_fill_keys(array_flip($unfilteredData), 'INT')
));
$result = array_values($a4['stuff']);
}
else
{
$result = array();
}