Now we'll continue by adding some user input validation. At the very top of form_mail.
php add some
PHP tags (<?
php ?>) and then we can start coding.
The first thing we want to do is declare and initialize some variables that we will be using later in our script. The $required_fields array can be adjusted (for example, you could remove the 'email' field if you don't think it's necessary to know the email of the person contacting you). The $to_address variable should be changed to the email to which you want the contact requests to be sent to.
- PHP: Select all
// declare and initialize some variables
$name=$email=$subject=$message=$error_message='';
$invalid_fields=array();
$required_fields=array('name','email','message');
$validated=array();
$to_address='blub@bla.com'; // your email address goes here
The next chunk of code checks if anything was posted and validates the user input:
- PHP: Select all
// validate $_POST array
if(count($_POST)>0) { // was something posted?
foreach($_POST as $key=>$value) { // loop through the $_POST array
if(in_array($key,$required_fields)&&$value=='') { // check if a required field is empty
// add that field to the $invalid_fields array
array_push($invalid_fields,$key);
// and append the error message to the $error_message variable
$error_message.='<p>Please enter a'.(preg_match('/^[aeiouy]/',$key)?'n':'').' '.$key.'.</p>';
}
// field is not in the $invalid_fields array?
if(!in_array($key,$invalid_fields)) {
// copy it to the $validated array
$validated[$key]=htmlspecialchars($value);
}
}
} else { // make everything invalid so that the form is outputted and not the thankyou message
$invalid_fields=$required_fields;
}
Some explanations:
- PHP: Select all
foreach($_POST as $key=>$value) { // loop through the $_POST array
This line lets us look at each index of the $_POST array. During each iteration, the value of the current index is stored in $value and the name of the current index is stored in $key. For example, when Justin Timberlake wants to contact you and submits the form, the first value in the $_POST array would be $_POST['name'] == 'Justin Timberlake' so during the first iteration of the FOREACH loop, $key == 'name' and $value == 'Justin Timberlake.'
- PHP: Select all
if(in_array($key,$required_fields)&&$value=='') { // check if a required field is empty
In this IF statement we check if the current value of $key is in the $required_fields array. If it is then we check if it is empty ($value == '') because a required field MUST contain a value.
- PHP: Select all
(preg_match('/^[aeiouy]/',$key)?'n':'')
This little inline IF isn't really necessary, it just raises the Usability. The regular expression checks to see if the value stored in $key starts with a vowel and if it does, "a" becomes "an" (ex: "a name" or "an email").
- PHP: Select all
$invalid_fields=$required_fields;
If nothing was posted, we set the $invalid_fields equal to the $required_fields. I'll explain why in my next post....