Code

Coding, Programming & Algorithms, Tips, Tweaks & Hacks
Search

Sponsored Ads

One-liner check for the existence of all required fields from a POSTed form

If you have a simple contact / registration form for a non-CMS / non-framework website with many input fields, it becomes cumbersome to do a server check if all fields passed through doing isset for every field. Many people just check for the existance of a single POST field, but for security reasons, it is better to check for the existence of all required fields.

PHP
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['phone']) && isset($_POST['message']))
{
    # POSTed
    # Process form
}
PHP

What if there were 20 fields ? That'll be one long line of issets.
array_diff is a built-in array function in PHP that computes the difference between arrays - it returns an array containing all the entries from the first array that are not present in any of the other arrays.
All we need to check is if the list of required fields are all present as keys in $_POST - this is easily achievable by checking against array_keys of $_POST.
And finally for the count - if all required fields are present in the $_POST's keys, it'll return 0 which is what we want and how we can confirm that all POST field values got sent through.

PHP
$requiredFields = array('name','email','phone','message');
if (count(array_diff($requiredFields, array_keys($_POST))) == 0)
{
    # POSTed
    # Process form
}
PHP
Vanakkam !

0 comments: