PHP Email Contact Form
I've had a couple inquiries about the code I use for my Email Me form, so I've decided to post the code here for anyone who'd like to use/adapt it.
2008/06/23: Replaced original email address format check with the PHP filter_var() function. This means that the minimum PHP version required is 5.2.0. (If you are on a host still running PHP4, you really should either move to a new host or get them to upgrade, as PHP4 is no longer being supported and not even security patches will be issued after August 2008.)
2008/05/12: I've updated this page to reflect the latest code I'm now using. I've decided to lose the "Captcha" image and input field, and instead include a couple "invisible" fields that legitimate users should neither see nor worry about, but hopefully will still stop the majority of spam-bots.
The only thing you need to add is the "thank you" page, which can be a plain HTML page if you want. On a successfully sent email, the script will redirect to that page. I use a "meta redirect" in mine just to help prevent users from accidentally resubmitting via the Refresh button/key.
The Form Page and Form-Handler
<?php
###############################################################################
#
# mail.php - general-purpose email form and script
#
# requires PHP version >= 5.2.0
#
# copyright 2005-2008 by Charles Reace
#
# This software available as open source software under the Gnu General Public
# License: http://www.gnu.org/licenses/gpl.html
#
###############################################################################
###############################################################################
# user-defined variables - update for your email address(es)
###############################################################################
session_start();
# link to "thank you" page:
$thanks = "http://www.example.com/thanks.php";
# Modify the following variable to specify where emails will be sent.
$to = "name@example.com";
# uncomment and edit the next line if you want to cc someone:
# $cc = "name@example.com";
# uncomment and edit the next line if you want to bcc someone:
# $bcc = "name@example.com";
#################################
# end of user-defined variables #
#################################
# Init. some variables:
$error = "";
$success = false;
# process form if submitted:
if(isset($_POST['submit']))
{
foreach($_POST as $key => $val)
{
if(empty($_POST[$key]) and $key != 'id')
{
$error .= "You must enter a value for " . ucwords(str_replace("_", " ", $key)) .
". ";
}
else
{
if(get_magic_quotes_gpc())
{
$_POST[$key] = stripslashes($val);
}
}
if($key != 'message')
{
$_POST[$key] = preg_replace('/[\r\n]/', ' ', $val);
}
}
if($_POST['email_address'] != $_POST['repeat_email'])
{
$error .= "Email Address is not the same as Repeat Email. ";
}
elseif(filter_var($_POST['email_address'], FILTER_VALIDATE_EMAIL) == false OR
filter_var($_POST['email_address'], FILTER_SANITIZE_EMAIL !== $_POST['email_address']))
{ // added 'SANITIZE' to deal with 'FILTER' bug when last character is newline
$error .= "'{$_POST['email_address']}' does not appear to be a valid email address. ";
}
if($_POST['id'] !== '')
{
$error .= ' Invalid form data received.';
}
if($_POST['token'] != $_SESSION['token'])
{
user_error("Post '".$_POST['token']."' != '".$_SESSION['token']."'");
$error .= ' Spam robot check failed. Make sure cookies are enabled for this site, or this form will not work.';
}
unset($_SESSION['token']);
if(empty($error)) # no errors in input, so go ahead and email it.
{
$headers = "From: " . preg_replace('/[\r\n]+/', ' ', $_POST['email_address']);
if(!empty($cc))
{
$headers .= "\r\nCc: $cc";
}
if(!empty($bcc))
{
$headers .= "\r\nBcc: $bcc";
}
$headers .= "\r\nX-Mailer: PHP/" . phpversion();
$msg = "From {$_POST['name']} ({$_POST['email_address']})";
$msg .= "\n\n\n{$_POST['message']}";
$result = @mail($to, $_POST['subject'], $msg, $headers);
if(!$result)
{
$error = "There was an unknown error while attempting to send your email.";
}
else
{
header("Location: $thanks");
}
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang='en'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'>
<title>Email Me</title>
<style type="text/css">
<!--
/* for any error messages */
.error { color: red; }
-->
</style>
</head>
<body>
<?php
if(!empty($error))
{
echo "<p class='error'>$error</p>\n";
}
?>
<h2>Email Me</h2>
<form action='<?php echo $_SERVER['PHP_SELF'] ?>' method=post>
<fieldset>
<legend>Your Contact Information</legend>
<p style='display:none'>Do not enter anything in this field: <input type='text' name='id'>
<input type="hidden" name="token" value="<?php
$_SESSION['token'] = uniqid();
echo $_SESSION['token'];
?>">
</p>
<p><label for='name' style="display: block; float: left; width: 9em;">Name:</label>
<input type='text' name='name' id='name' size='30' maxlength='40'<?php
if(!empty($_POST['name']))
{
echo "value='{$_POST['name']}'";
}
?>></p>
<p><label for='email_address' style="display: block; float: left; width: 9em;">Email Address:</label>
<input type='text' name='email_address' id='email_address' size='30' maxlength='40'<?php
if(!empty($_POST['email_address']))
{
echo "value='{$_POST['email_address']}'";
}
?>></p>
<p><label for='repeat_email' style="display: block; float: left; width: 9em;">Repeat Email:</label>
<input type='text' name='repeat_email' id='repeat_email' size='30' maxlength='40'<?php
if(!empty($_POST['repeat_email']))
{
echo "value='{$_POST['repeat_email']}'";
}
?>></p>
</fieldset>
<fieldset>
<legend>Message</legend>
<p><label for='subject' style="display: block; float: left; width: 9em;">Subject:</label>
<input type='text' name='subject' id='subject' size='50' maxlength='60'<?php
if(!empty($_POST['subject']))
{
echo " value='{$_POST['subject']}'";
}
?>></p>
<p><label for='message'>Message:</label><br>
<textarea name='message' id='message' cols='50' rows='8'
style="width: 375px"><?php
if(!empty($_POST['message']))
{
echo $_POST['message'];
}
?></textarea></p>
<p style="text-align: center;"><input type='submit' name='submit' value="Send Email"></p>
</fieldset>
</form>
</body>
</html>