There is filter_input_array, which helps to consolidate some parts of it.
For example:
$args = array(
'year' => array(
'filter' => FILTER_VALIDATE_INT,
'options' => array('min_range' => 1900, 'max_range' => 2100)
),
'month' => array(
'filter' => FILTER_VALIDATE_INT,
'options' => array('min_range' => 1, 'max_range' => 12)
),
'day' => array(
'filter' => FILTER_VALIDATE_INT,
'options' => array('min_range' => 1, 'max_range' => 31)
)
);
$myInputs = filter_input_array(INPUT_POST, $args);
You will then end up with the following array:
array
'year' => int 2011
'month' => int 12
'day' => int 3
And yes, you can also incorporate other POST data in that array too. For example:
$args = array(
...,
'item_name' => FILTER_SANITIZE_STRING,
...,
);
You can then safely assign those from there to other variables:
$year = $myInputs['year'];
$month = $myInputs['month'];
$day = $myInputs['day'];
If some parts of it don’t match the validation, you end up with:
array
'year' => int 2011
'month' => boolean false
'day' => int 3
So, after assigning the values, checking if any of those variables are invalid can then be usefully performed. You can then throw a suitable exception:
In some cases it can be very useful to throw an exception instead of hiding or disguising the error.
if (empty($year) || empty($month) || empty($day)) {
throw new OutOfRangeException('Invalid date argument.');
}
// carry on with date stuff
Code execution will then stop at that exception, so there’s no need to wrap the rest of the code in an else condition.
You do not want to use just $year + ‘-’ + $month + ‘-’ + $day as the date, because you then end up with formatting problems such as:
2011-10-5
2011-11-25
2011-5-11
2011-6-5
If anything makes the mistake of treating those as strings, sorting them then becomes a nightmare.
So instead, ensure that your dates are all formatted in a manner that guarantees that they are all consistant:
2011-05-11
2011-06-05
2011-10-05
2011-11-25
So, once you have the appropriate year month and day values, you want to put them together as a date with leading zeros in their proper place, so this looks like a job for the date function. You would use Y for the full year, m for a numeric month with leading zeros, and d for the day with leading zeros.
That is, ‘Y-m-d’
But we need a timestamp to create that date from. Fortunately strtotime is very good at that job, and can accept many different types of dates, even things like “+1 week 2 days” or “next Thursday”
So we have the following:
$timestamp = strtotime($year + '-' + $month + '-' + $day);
$sqlDate = date('Y-m-d', $timestamp);
Now $sqlDate contains a nicely formatted version of ‘2011-06-05’ which you can make use of from there.