PHP Basics: Quick Form Data Checks

Lots of frameworks do a great job handling this task for you, and you should take a look at Symfony Forms.

That being said, one of the most common tasks of a Web Developer will usually be working with Forms. You’ll create hundreds of forms and in turn, write hundreds of pieces of code to handle some type of user submitted data.

Early on this became the worse part of my job. So I started to use a quick way to handle post data. What’s not shown here is the very very very important step of validating the user input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?php
// ... in some function ....
$valid = true; // innocent until proven guilty
$errors = array(); // errors array
$clean = ['first_name' => null, 'last_name' => null]; // where we keep good validated values.
foreach($_POST as $key => $val) {
switch($key) {
case 'first_name':
// Do validation!!!
// Place holder function name for now.
if(validateString($val) == false) {
$valid = false; // we're no longer valid.
$errors[] = "You're missing your first name!"; // prime up an error message for our user
} else {
$clean[$key] = $val;
}
break;
case 'last_name':
// ... etc etc ...
break;
}
}
if($valid == false) {
// Send the user back to fix their issues!
} else {
// We now have an entire row of values we know we want to
// save somewhere. We can now either create a PDO statement
// to insert them, or use the clean value array somewhere else.
}

Two pieces of code are at work here. The foreach() will iterate over the values of the form, while the switch case let’s us use a boolean flag to determine if the data is correct. Unfortunately I still come across lengthy if else/else if/else in some PHP code out in the wild.

The only real missing piece from this shortcut is ensuring all of the $_POST values are present. This could be done by comparing all of the values in your $clean array are present in $_POST