PHP Email Contact Page

Fast and easy email contact form in PHP with just a single file!

I've written and rewritten what seems like zillions of these little PHP contact forms that email the website owner when someone contacts them through their website. I finally built it more modular and portable and this is the very barebones version.

This code is the core of my own contact script, save for the captcha stuff and some other little enhancements. Also, I have not tested this code in PHP4 earlier. I use PHP5 on all my projects, now, and I don't bother testing with 4. Most hosting companies have a method for switching your interpreter to 5. I would suggest you move forward.

PHP Source Code

<?php

/*****************************************************************************************
 onesandzeros.biz PHP Mail-O-Matic 76ª
 written by Andy Frey (andy@onesandzeros.biz)
 version 0.9.5 (2007-07-17)
 Please give credit if you use this neato little thing. If you would be
 so kind as to put this little micro banner on your site and link it
 back to me, that would be super-splendid:
    <a href="http://onesandzeros.biz/" alt="Phoenix, Arizona PHP programmer Andy Frey">
        <img src="http://onesandzeros.biz/images/banners/ozmicro.png" style="border:none" />
    </a>
******************************************************************************************/


// change this to your website domain name
define( 'DOMAIN_NAME', 'onesandzeros.biz' );

// change this to the email address that will receive the contact information
define( 'EMAIL_TO', 'andy@onesandzeros.biz' );

// change this to the reader-friendly title of your form (shows up in emails, too)
define( 'FORM_TITLE', 'The onesandzeros.biz Contact Form' );

define( 'MSG_BAD_EMAIL',
    // what to say to the user if their email address is bad
    '<p style="font-weight:bold;color:#990000">The email address you entered is invalid.</p>'
);

define( 'MSG_EMPTY_NAME',
    // what to say to the user if their name is empty
    '<p style="font-weight:bold;color:#990000">Please enter your name.</p>'
);

define( 'MSG_EMPTY_MESSAGE',
    // what to say to the user if the message is empty
    '<p style="font-weight:bold;color:#990000">Your message is blank. Please send <strong>something</strong> to me.</p>'
);

define( 'MSG_MAIL_WORKED',
    // what to say to the user if the mail gets sent OK
    '<p style="font-weight:bold;color:#009900">Thank you for contacting me! If required, I will reply back to you.</p>'
);

define( 'MSG_MAIL_DIDNT_WORK',
    // what to say to the user if the mail() function doesn't work
    '<p style="font-weight:bold;color:#990000">There was a problem sending the email message. Please contact ' . EMAIL_TO . ' through a regular email application. Sorry for the inconvenience.</p>'
);


//***************************************************************
// don't touch code below here unless you know what you're doing!
//***************************************************************

// returns the current time formatted: 2007-07-17 15:24:06
function now() {
    return date( "Y-m-d H:i:s" );
}

// quick and dirty conversion to html from plain text
function txt2html( $text ) {
    $text = "<p>" . str_replace( "\r\n", "<br/>", $text ) . "";
    $text = "" . str_replace( "<br/><br/>", "</p><p>", $text ) . "";
    return "" . str_replace( "<br/><li>", "<li>", $text ) . "";
}

// return 0 if $e isn't a valid email, 1 if it is
function isValidEmail( $e ) {
    return preg_match( '/^[_a-z0-9-][^\(\)\<\>\@\,\;\:\\\"\[\] ]*\@([a-z0-9\-]+\.)+[a-z]{2,4}$/i', $e )
}

// output mail header(s) with a string or an array of strings
function mailHeader( $h ) {
    $out = '';
    if( is_array( $h ) ) {
        foreach( $h as $l ) {
            $out .= $l . "\r\n";
        }
    } else {
        $out = $h . "\r\n";
    }
    return $out;
}

$msg = "";
$form = array();

if( !empty( $_REQUEST['email'] ) ) {

    // reassign form data to make code easier to read
    $form = $_REQUEST['email'];

    // check the information to be sure we have what we need
    if( !isValidEmail( $form['address'] ) ) {
        $msg = MSG_BAD_EMAIL;
    }
    if( !strlen( $form['name'] ) ) {
        $msg .= MSG_EMPTY_NAME;
    }
    if( !strlen( $form['message'] ) ) {
        $msg .= MSG_EMPTY_MESSAGE;
    }

    // if there isn't a message (no problems), build the email
    if( !strlen( $msg ) ) {
        // fix any incomplete fields
        if( !strlen( $form['subject'] ) ) {
            $form['subject'] = '[No Subject]';
        }
        // used to separate section of a multi-format email message (plain text vs. html format)
        $boundary = DOMAIN_NAME . '_' . md5( $form['name'] . "_" . time() . "_reset" ) . '_' . time();
        // headers to stick into the message for proper routing, debugging, character set, etc.
        $headers = mailHeader(
            array(
                'From: ' . FORM_TITLE . ' <' . EMAIL_TO . '>',
                'Reply-To: ' . $form['name'] . ' <' . $form['address'] . '>',
                'X-Mailer: ones&amp;zeros PHP Mail-O-Matic 76&trade;',
                'MIME-Version: 1.0',
                'Content-Type: multipart/mixed; boundary="' . $boundary . '";',
                'charset="iso-8859-1"',
                'Content-Transfer-Encoding: 7bit'
            )
        );
        // build the multi-part internet mail message (MIME)
        $message =

            // what to say to someone who doesn't have a modern email client
            'Please upgrade your email client. Seriously. If you can read this, you are using a ' .
            'ridiculously old email client. Do you own a microwave?\n\n' .
            '--' . $boundary . "\r\n" .

            // this is the plain text version of the message
            mailHeader( array( 'Content-Type: text/plain; charset="iso-8859-1"', 'Content-Transfer-Encoding: 7bit' ) ) .
            'You have received a message from ' . FORM_TITLE . ':' . "\n\n"
            'From: ' . $form['name'] . ' (' . $form['address'] . ')' . "\n" .
            'Date: ' . now() . "\n" .
            'Subject: ' . $form['subject'] . "\n\n" .
            $form['message'] . "\r\n" .
            '--' . $boundary . "\r\n" .

            // this is the HTML version of the message
            mailHeader( array( 'Content-Type: text/html; charset="iso-8859-1"', 'Content-Transfer-Encoding: 7bit' ) ) .
            '<p>You have received a message from <strong>' . FORM_TITLE . '</strong> contact form:' . "</p>\n\n"
            '<div style="background-color: #EEEEEE; border: 1px solid #999999">' .
            'From: <strong>' . $form['name'] . '</strong> (' . $form['address'] . ')' . "<br />\n" .
            'Date: <strong>' . now() . '</strong>' . "<br />\n" .
            'Subject: <strong>' . $form['subject'] . '</strong>' . "</div>\n\n" .
            txt2html( $form['message'] );

        // now, attempt to mail the message out through the PHP mail() function
        if( mail( EMAIL_TO, 'Message from ' . FORM_TITLE, $message, $headers ) ) {
            // it worked!
            $msg = MSG_MAIL_WORKED;
            // clear the form field variables for a fresh start (empty form)
            $form = array();
        } else {
            // it didn't work.  ):
            $msg = MSG_MAIL_DIDNT_WORK;
        }
    } // end of !strlen( $msg )
}

//
// Below is the top of your web page HTML source code
//

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" version="-//W3C//DTD XHTML 1.1//EN" xml:lang="en">
<head>
    <meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
    <link href="/includes/css/ozStyle.css.php" type="text/css" rel="stylesheet" />
    <title>Simple PHP Email Contact Form Demo</title>
</head>

<body style="margin:10px">

<h1><?=FORM_TITLE?></h1>


<?= !empty( $msg ) ? $msg : '' ?>


<form method="post" style="margin: 0px; padding: 0px;">

    <p>Your name:<br />
    <input name="email[name]" type="text" value="<?=$form['name']?>" size="40" maxlength="100"></p>

    <p>Email address:<br />
    <input name="email[address]" type="text" value="<?=$form['address']?>" size="60" maxlength="255"></p>

    <p>Subject:<br />
    <input name="email[subject]" type="text" value="<?=$form['subject']?>" size="60" maxlength="255"></p>

    <p>Message:<br />
    <textarea name="email[message]" rows="10" cols="50"><?=$form['message']?></textarea></p>

    <p><input type="submit" value="submit" /></p>

</form>


</body>

</html>