PHP comes with built in validation filters, so you can validate emails, numbers and urls and more without writing any code.
To use it, we pick a filter and pass it to the filter_var() function together with the data we want to validate.
Example 1 – Email validation
$string = 'email@example.com'; var_dump(filter_var($string, FILTER_VALIDATE_EMAIL));
When validation succeeds, we get the string back. But what if the validation is unsuccessful?
$string = 'definitely-not^an_email'; var_dump(filter_var($string, FILTER_VALIDATE_EMAIL));
Great, we get false back! Now to put it together:
$string = 'firstname.lastname@example.org'; if(filter_var($string, FILTER_VALIDATE_EMAIL)!==false) echo "Totally validated!";
Example 2 – Validating an integer with a minimum and maximum values
Some validators have options. The FILTER_VALIDATE_INT validator has two options, min_range and max_range. You can specify these to limit which integers will be valid. (In our case, only 10 – 20 is considered valid).
$number = 15; var_dump(filter_var($number, FILTER_VALIDATE_INT, array('options' => array('min_range' => 10, 'max_range' => 20))));
Great! The number got validated and we got it back. If validation would have failed we would have gotten bool(false), like in Example 1.
That covers basic validation with PHP. Before saving any user-entered data, you should use sanitize filters to sanitize the data. Sanitization filters work similarly to validation filters – the difference is that sanitization filters alters the data you send to filter_var to make it conform to the filter criteria.