Contact Form Tutorial

David Carr

Tutorials PHP & MySQL

Need a contact form for your site? This tutorial shows you how to create one.

This tutorial assumes you have a basic knowledge of PHP there are other tutorials on this site that explains some of the mechanics used here.

The contact form will be sent to your email address once the form is completed.

First we check that the form has been submitted: 

//This code runs if the form has been submitted

if (array_key_exists('submit', $_POST))
{

If the form has been submitted we check to make sure the fields are not empty and trim any white space.

We first check the name field We make sure the input is less then 3 but not more then 20 char actors using the function strlen (string length) if the char actors are less or more then specified then an error is set but its not printed out just yet.

// check fields are not empty
$name = trim($_POST['name']);
if (strlen($name) < 3) {
$error['name'] = 'Name Must be more then 3 charactors.';
}

if (strlen($name) > 20) {
$error['name'] = 'Name Must be less then 20 charactors.';
}

Then we check for a valid email address:

// check for valid email address
$email = $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  $error[] = 'Please enter a valid email address';
} 

We then check the message input section to make sure its been filled in the same way we checked the name field.

// check fields are not empty
$message = trim($_POST['message']);
if (strlen($message) < 3) {
$error['message'] = 'Message Must be more then 3 characters.';
}

Now we make sure there's no errors set and proceed if there are no errors if there is errors they will be printed above the form.

// if validation is okay then carry on
if (!$error ) {

If no errors set send the email. Change the email address to your email address you want to use to get the form details.

For the subject field I've typed in Contact for &quot;.$_SERVER['HTTP_HOST'].&quot; This will get the server address its come from like: www.example.com.

The body is the form details this can be laid out any way you like to put text on a new line use (new line)

Addtionalheaders will include your email address so when you receive the email it will display your email address in the from field.

Lastly we check to see if the email has been sent using an if statement and if the email has been sent then we set the variable $sent to true.

We then close the brackets for validation and for submitted. 

//send email
$to = "example@domain.com";
$subject = "Contact for ".$_SERVER['HTTP_HOST']."";
$body = "on ".date('M j, Y')." Information from contact form: Name: $name With the email address of $email Wrote this message: $message";
$additionalheaders = "From: <example@domain.com> ";
$additionalheaders .= "Reply-To: example@domain.com";
if(mail($to, $subject, $body, $additionalheaders))
{
$sent = true;
}
} // end valadation
}// end submit

Once the email has been sent show a success message.

// If mail is sent
if (isset($sent)) {
echo "<p>Thank you </p>";
echo "<p>We will be in touch shortly </p>";

} else { // mail not sent show form

If the email has not been sent and errors are set show the errors then display the form.

echo "<p>Use this contact form for general enquires</p>";

echo "<p>I hate spam and I'm sure you do too, so don't worry your email address will <strong>NOT</strong> be passed on to any third party's </p>";

// show any errors if set
echo "<blockquote>";

if (isset($error['name'])) {
echo "<p><span class="warning">".$error['name']."</span></p> ";
}

if (isset($error['email'])) {
echo "<p><span class="warning">".$error['email']."</span></p> ";
}

if (isset($error['message'])) {
echo "<p><span class="warning">".$error['message']."</span></p> ";
}

echo "</blockquote>";

Now we show the for. The form will reload the same page once its sent using 

action="<?php echo $_SERVER['PHP_SELF']; ?>"

I've always set the form to be a sticky form so it there is an error the form keeps the inputted date using the value in the input field 

<?php if(isset($error)) {echo "value='$name'";} ?>

After the form is finished we close the else statement that is still open.

<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<legend>Contact</legend>
<p><label>Name:</label><input name="name" type="text" maxlength="20" <?php if(isset($error)) {echo "value='$name'";} ?> /></p>
<p><label> Email:</label><input name="email" type="text" maxlength="2550" <?php if(isset($error)) {echo "value='$email'";} ?> /></p>
<p><label>Message:</label><textarea name="message" cols="50" rows="10" id="message"><?php if(isset($error)) {echo $message;} ?></textarea></p>
<p><input type="submit" name="submit" value="Send Message"></p>
</fieldset>
</form>
<?php } ?>

Here is the full code:

<?php
//This code runs if the form has been submitted
if (array_key_exists('submit', $_POST))
{
// check fields are not empty
$name = trim($_POST['name']);
if (strlen($name) < 3) {
  $error['name'] = 'Name Must be more then 3 characters.';
}

if (strlen($name) > 20) {
  $error['name'] = 'Name Must be less then 20 characters.';
}

// check for valid email address
$email = $_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
  $error[] = 'Please enter a valid email address';
} 

// check fields are not empty
$message = trim($_POST['message']);
if (strlen($message) < 3) {
  $error['message'] = 'Message Must be more then 3 characters.';
}

// if validation is okay then carry on
if (!$error ) {
//send email
$to = "example@domain.com";
$subject = "Contact for ".$_SERVER['HTTP_HOST']."";
$body = "on ".date('M j, Y')." Information from contact form: Name: $name With the email address of $email Wrote this message: $message";
$additionalheaders = "From: <example@domain.com> ";
$additionalheaders .= "Reply-To: example@domain.com";
if(mail($to, $subject, $body, $additionalheaders))
{
  $sent = true;
}

} // end validation
}// end submit

// If mail is sent
if (isset($sent)) {
 echo "<p>Thank you </p>";
 echo "<p>We will be in touch shortly </p>";
} else { // mail not sent show form
 echo "<p>Use this contact form for general enquires</p>";
 echo "<p>I hate spam and I'm sure you do too, so don't worry your email address will <strong>NOT</strong> be passed on to any third party's </p>";

// show any errors if set

echo "<blockquote>";
 if (isset($error['name'])) {
   echo "<p><span class="warning">".$error['name']."</span></p> ";
}

 if (isset($error['email'])) {
   echo "<p><span class="warning">".$error['email']."</span></p> ";
 }

 if (isset($error['message'])) {
   echo "<p><span class="warning">".$error['message']."</span></p> ";
 }

echo "</blockquote>";
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<fieldset>
<legend>Contact</legend>
<p><label>Name:</label><input name="name" type="text" maxlength="20" <?php if(isset($error)) {echo "value='$name'";} ?> /></p>
<p><label> Email:</label><input name="email" type="text" maxlength="2550" <?php if(isset($error)) {echo "value='$email'";} ?> /></p>
<p><label>Message:</label><textarea name="message" cols="50" rows="10" id="message"><?php if(isset($error)) {echo $message;} ?></textarea></p>
<p><input type="submit" name="submit" value="Send Message"></p>
</fieldset>
</form>
<?php } ?>

 

Read articles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Copyright © 2006 - 2024 DC Blog - All rights reserved.