2. PHP Form Handler
The important characteristics of a form handler is that it verifies that the required
variables have been set, and that they have appropriate values. Remember to be
thorough as this is your last (only real) line of defence against malicious scripts.
Here we are detecting a POST event and extracting the values directly from the
PHP $_POST array for testing:
<?PHP
// form handler
if($_POST && isset($_POST['sendfeedback'], $_POST['name'],
$_POST['email'], $_POST['subject'], $_POST['message'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if(!$name) {
$errorMsg = "Please enter your Name";
} elseif(!$email || !preg_match("/^\S+@\S+$/", $email)) {
$errorMsg = "Please enter a valid Email address";
} elseif(!$message) {
$errorMsg = "Please enter your comment in the Message box";
} else {
// send email and redirect
$to = "feedback@example.com";
if(!$subject) $subject = "Contact from website";
$headers = "From: webmaster@example.com" . "\r\n";
mail($to, $subject, $message, $headers);
header("Location: http://www.example.com/thankyou.html");
exit;
}
}
?>
All HTML form elements, aside from unselected checkboxes and radio buttons, will
appear in the $_POST array, even if the value is blank. This includes the submit button,
which in this case we have named sendfeedback. Naming the button is useful in case
there are multiple forms on the page. The first thing the form handler does is check
that all the fields in our form, including the button, appear in the POST array. Then
we extract the relevant values for testing.
The testing here is fairly rudimentary. In reality we have special functions for
validating email addresses and other data types - as will most JavaScript libraries.
We also have more advanced functions for sending email. For public-facing forms