PHP Sanitation and Validation
The intention for this post is to record the PHP Sanitation and Validation techniques I’ve used against various variable types for future reference. Until now I’ve always found myself digging through code to remind myself of what I did last time.
There are two key approaches regular expressions and the filter_var function from PHP. If you are going to use the filter_var function provided with PHP you should use both Sanitize and Validate. If you are unsure of the difference you should look here but you are too lazy right so very quickly:
- Sanitize – cleans out the input incase the user ‘accidentally’ typed a wrong char.
- Validate – makes sure it fits the right format.
I’ve never had much success with this approach as the email and float filters seem to reject valid parameters.
Validating Floats
To validate floats where validateRegexField
is a function of mine (See Bottom) I call the function with
$myError = validateRegexField($myFloat,"^[-+]?([0-9]*\.[0-9]+|[0-9]+)$","MyFloatName", $hasError);
Note how I am using the ^ and $
to prevent other text contaminating the field. If you are interested in what I mean take them out and try 4.5 bad which will then validate. Put them back in and it will error. I’m also passing the first and last variables by reference so I can change their values in the function (bottom of page).
Dates
General consensus here is that Regex is not the best way to do this because it fails to find some types of invalid field. This method attempts to turn the date into a string and then back into a date again. This leaves our users free to enter a date in whatever format they like and we then just rearrange it. Sadly it doesn’t work for when someone enters only yyyy-mm as dd default to 01 so I have added in a length check for 10. This function is based on information found on the checkdate docs page and iamcanadian1973 in particular.
//Validate Date
function validateDate(&$data,$name,&$hasError) {
if ($data === '') {
$hasError = true;
return "You forgot to enter the " . $name;
}
$stamp = strtotime( $data );
if (!is_numeric($stamp) || strlen($data) != 10) {
$hasError = true;
return "You entered an invalid " . $name. " with '" . $data ."'";
}
//Lets move to check date
$month = date( 'm', $stamp );
$day = date( 'd', $stamp );
$year = date( 'Y', $stamp );
if (!checkdate($month, $day, $year)) {
$hasError = true;
return "You entered an invalid " . $name. " with '" . $data ."'";
}
//Return a well formatted date.
$data = date ('Y-m-d', $stamp);
return false;
}
validateRegexField Function
This validateField
function takes some variables and checks for a valid entry.
//Regex Validation function
function validateRegexField($data,$regex,$name,&$hasError) {
if ($data === '') {
$hasError = true;
return "You forgot to enter the " . $name;
} else if (!eregi($regex, $data)) {
$hasError = true;
return "You entered an invalid " . $name;
}
return false;
}