Building a Secure Contact Form

4.14 (129)

Sending the Email

Now that we have our contact form, we need to code the PHP that is going to parse the input from the form. We have a few criteria to meet; we must send the email to the correct department making sure for the email to never be shown on the website, show an error or confirmation page after trying to send the email, and also validating the input.

Firstly, we should parse the input and select the email address that we are going to send the email to. We must also at the same time, get ready to send the email and send it.

The basics
<?php

$emailSubject 
$_POST['Subject'];
$emailMessage $_POST['Message'];
$emailFrom $_POST['Email'];
$emailFromName $_POST['Name'];

$emailList[1] = 'comments@example.com';
$emailList[2] = 'advertising@example.com';
$emailList[3] = 'privacy@example.com';

$emailTo $emailList[$_POST['Reason']];

if (!empty(
$emailFrom)) {
$emailHeaders 'From: "' $emailName '" <' $emailFrom '>';
} else {
    
$emailHeaders 'From: "Your Name" <webmaster@example.com>';
}

/* Send Email */
mail ($emailTo$emailSubject$emailMessage$emailHeaders);

?>


This script pretty much lacks all error checking so I wouldn't advice your to use this script, however, it is functional. What we have done here, is created an array inside our script to hold a list of possible emails addresses to send the email to. When the user selects the department they are sending to, it in effect selects an email address, as the numbers in the form correspond with the indexes in the array. Using this method, if we wanted to add another contact reason / department, then we would have to modify the form, and also at the same time add an extra element to the array.

Notice how our email addresses are quite normal looking, this is not very good as people can guess these and send emails to your email anyway. A solution to this is to use odd looking or random email addresses. As the user doesn't have to remember them, or type them, then it doesn't matter.

We have actually written the code here to send the email using the mail() function. This function is quite simple to use in effect but can be a little annoying sometimes, it really depends what platform you are on, and your PHP / mail settings. Here is the general format of the mail() function:

bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]] )


You can ignore the last parameter as it is not important and rarely used. The first four are important though. They state we have to pass an email address to send to, a subject, a message and optionally some email headers. The headers are quite important as they allow us to set some options about the email, like, who the email is from.

In our example, we have set the email from the user's email address if they have supplied it. Otherwise, it is set from your own details (make sure you change these). Notice the format of the From header. This is the standard header, although sometimes you can / should leave out the double quotes ("). You can only tell by sending yourself a test email add testing what the 'from' field of the email says. If it looks normal, then leave the quotes, otherwise remove them.

Basic Validation and User Confirmation


Ideally, we should validate that the user has actually entered a message, a subject and chosen a valid department to send the email to. We should also probably validate the email address; however, I will cover that in the next page.

We must also give the user confirmation of the email being sent, or of an error occurring, that they know the status of their email address. This is all fairly simple to add to our script, just laborious.

Full Code
<html>
<head>
<title>Contact Us</title>
</head>
<body>

<?php
$emailSubject 
$_POST['Subject'];
$emailMessage $_POST['Message'];
$emailFrom $_POST['Email'];
$emailFromName $_POST['Name'];

$emailList[1] = 'comments@example.com';
$emailList[2] = 'advertising@example.com';
$emailList[3] = 'privacy@example.com';



if (empty(
$emailSubject)) {
    echo 
'You must enter a valid subject.';
} elseif (empty(
$emailMessage)) {
    echo 
'You must enter a message to send to our team.';
} elseif ((
$_POST['Reason'] < 1) || ($_POST['Reason'] > 3)) {
    echo 
'You have selected an invalid department.';
} else {
    
    
$emailTo $emailList[$_POST['Reason']];
    
    if (!empty(
$emailFrom)) {
        
$emailHeaders 'From: "' $emailName '" <' $emailFrom '>';
    } else {
        
$emailHeaders 'From: "Your Name" <webmaster@example.com>';
    }
    
    
/* Send Email */
    
if (mail($emailTo$emailSubject$emailMessage$emailHeaders)) {
        echo 
'You message has been sent!';
    } else {
        echo 
'There was an internal error whilst sending your email.<br>';
        echo 
'Please try again later.';    
    }
}
?>
</body>
</html>


This is a very long piece of code, however, it demonstrates our error checking to make sure that the required fields have been entered. It also shows the confirmation of sending to the user. If you want, you could tell the user about a special email address they could send to if they receive the internal error, however, note that you may start receiving spam from to this email address.
Rate this article: BAD 1 2 3 4 5   GOOD
<<     Page 2 of 3    >>

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!

Ads

PHPNerds Newsletter