Of Zen and Computing

How to Code a PHP Contact Form

Wednesday, December 12, 2007

A contact form is a very effective tool for someone who runs a Web site — one can protect their e-mail address from spammers, and allow visitors to easily get in touch. Some people might not be motivated enough to open up their e-mail client and compose a message, but may take the time to fill out a simple contact form.

If your server has PHP enabled, programming a contact form is a piece of cake. PHP has a built in mail function that simplifies the task of programmatically sending e-mail.

There is one caveat to programming your own contact form: malicious people often take advantage of insecure mail scripts and use them to send out spam. In this article, I will show you the necessary source code to implement a secure contact form in PHP.

<?php
/**
 * A PHP contact form.
 * Author: tom@ofzenandcomputing.com
 * Last revision: 11/19/2007 01:03
 * 
 * Mail header injection prevention based on comments from:
 *     http://www.php.net/mail
 *
 * E-mail validation regex from:
 *     http://www.regular-expressions.info/email.html
 */

// Replace you@example.com with your own e-mail address.
define('YOUR_EMAIL', 'you@example.com');

// If the user does not fill in a subject, this will be used.
define('DEFAULT_SUBJ', 'A message from your contact form');

// This is the maximum length of a subject, in characters.
define('MAX_SUBJ_LEN', 1000);

if (isset($_POST['mail'])) {
    $errors = array();
    
    // Sanitize the subject;
    if (preg_match('/(%0A|%0D|\\n+|\\r+)/i', $_POST['subj'])) {
        $errors[] = 'Your subject contains illegal characters.';
    } else {
        if (!strlen($_POST['subj']) || is_null($_POST['subj'])) {
            $subj = DEFAULT_SUBJ;
        } else {
            $subj = substr($_POST['subj'], 0, MAX_SUBJ_LEN);
        }
    }
    
    // Validate their e-mail address.
    if (!preg_match('/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $_POST['email'])) {
        $errors[] = 'Invalid e-mail address.';
    }
        
    
    // Validate the body.
    if (preg_match('/(%0A|%0D|\\n+|\\r+)(content-type:|to:|cc:|bcc:)/i', $_POST['body'])) {
        $errors[] = 'Your message body contains invalid characters.';
    }
    if (!strlen($_POST['body'])) {
        $errors[] = 'The body of your message was blank.';
    }

    if (count($errors)) {
        for ($i = 0; $i < count($errors); $i++) {
            printf('<div class="error">%s</div>', $errors[$i]);
        }
    } else {
        $headers = sprintf("From: %s\r\n", $_POST['email']);
        if (mail(YOUR_EMAIL, $subj, $_POST['body'], $headers)) {
            print '<p>Your message was sent.</p>';
        } else {
            print '<p>An error occurred while we were attempting to'
                .' send your message. Please try again later.</p>';
        }
    }
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<div>
    <label for="email">Your E-mail:</label>
    <input type="text" name="email" />
</div>
<div>
    <label for="subj">Subject:</label>
    <input type="text" name="subj" maxlength="<?php echo MAX_SUBJ_LEN;?>" />
</div>
<div>
    <label for="body">Your Message:</label>
    <textarea name="body" wrap="virtual"></textarea>
</div>
<div><input type="submit" name="mail" value="Send Message" /></div>
</form>

Customization

The first thing you absolutely must do is customize this script with your own e-mail address. Without your e-mail address, this script will not be able to send your messages. Replace you@example.com on line 15 with your own e-mail address.

This is a bare-bones contact form when it comes to style. I have not included any fancy markup, stylesheets, nor anything else related to aesthetics. You will probably want to make this look nice - particularly the error messages. Perhaps define div.error to be red, bold, or both. You will also need to add HTML headers and footers at the top and bottom of the script, which will make it blend in with your site’s design.

File under: Code

Digg icon StumbleUpon icon del.icio.us icon Facebook icon

Other articles related to this page

© 2006-2008 OfZenAndComputing.com
E-mail Disclaimer | Terms of Service & Disclaimer | Sitemap

Subscription Options
Search Our Archive of How-To Articles and Blog Posts