php contact form tutorial
Code Tutorial

PHP contact form tutorial

Hopefully you’re reading this because you are searching for a PHP contact form tutorial.

Let’s start with a little background information.

When I first started building websites I really struggled to get a working PHP contact form. It took me a while to figure out how to do it.

So with this PHP contact form tutorial I’ll show you how to easily get a working PHP contact form for your website. At the end of this guide you should have a working contact form on your web page.

Table of Contents:

  1. Introduction
  2. Prerequisites before we build the PHP form.
  3. Form Fields
  4. HTML Guide
  5. PHP Specifics
  6. Summary

I’ve added an image of another form I created for a client below. You should end up with something similar, depending on your CSS (cascading style sheet) skills.

PHP Contact Form example.
A PHP Contact Form example.

A Step by step guide to building a PHP Contact Form

Step 1:
You need to determine where you would like your PHP contact form. Most of the time it’s going to be on the contact us page, you can also use similar code to create a ‘subscribe’ form, so you could place that anywhere. For now, I’m going to assume you’ve created a ‘contact us’ page.

Step 2:
The PHP contact form needs some fields. These fields will contain the information that is going to be sent via e-mail. Be sure to keep it user friendly and quick to fill out. Users hate having large mundane forms to fill out! For this form we are going to use 4 fields and a submit button. The fields are as follows:
– Your Name
– Your E-mail Address
– Subject
– Message

To slim the form down further, you could even get rid of the ‘Subject’ field. The client I created this particular form for wanted a ‘Subject’ field.

The submit button will be labelled as ‘Send’.

The HTML Guide

Step 3:
Now that we understand what the fields will be, we can start to code the form. The first part of the code needs to be the HTML markup. We’ll need to create the fields in the HTML.

Here’s the complete HTML:

<form id=”contact-form” action=”mail.php” method=”post”>
<div class=”input-box”>
<input type=”text” name=”name” placeholder=”Your Name*”>
<input type=”email” name=”email” placeholder=”Your e-mail address*”>
</div>
<div class=”input-sub”>
<input type=”text” name=”subject” placeholder=”Subject*”>
</div>
<div class=”input-message”>
<textarea name=”message” placeholder=”Please type your message..*”></textarea>
</div>
<div class=”send-btn”>
<button type=”submit” class=”ml-btn btn-light btn-large”>Send</button>
</div>
</form>

The good thing about HTML is that it is really easy to read and understand what it’s doing. So let’s look at the HTML in more detail.

The first line, I’ve created the form and gave it an ID of contact-form and set the action to mail.php. The method will be post which means we are sending data. When the submit button is clicked it’ll call the mail.php form, build the e-mail and then send it.

The next four lines are for creating the name and email address fields. We start with a DIV tag and give that a class of input-box. A class can dictate a number of things, in this instance it’s the styling.

Styling Example of the contact form
Styling Example of the contact form

Then, we tell the form what data and data types to expect using the input type, name and placeholder tags.

<input type=”text” name=”name” placeholder=”Your Name*”>
<input type=”email” name=”email” placeholder=”Your e-mail address*”>

It’s fairly simple. For ‘Name’ we are expecting the user to enter plaint text and we set the placeholder to “Your Name*” and “Your e-mail address*”.

We also need to follow a similar methodology for the subject and message.

<div class=”input-sub”>
<input type=”text” name=”subject” placeholder=”Subject*”>
</div>
<div class=”input-message”>
<textarea name=”message” placeholder=”Please type your message..*”></textarea>
</div>

One thing to point out here is that the field type for message is textarea. It’s best to use textarea because it allows the user to enter a multi line message rather than have it all on one line.

The last few lines of the markup are all about the submit button.

<div class=”send-btn”>
<button type=”submit” class=”ml-btn btn-light btn-large”>Send</button>
</div>

Here, we define the class send-btn, which defines the styling (there are other styling attributes applied to the HTML that I haven’t covered) and we also define the button type to be submit. 

Styling example for a submit button.
Styling example for a submit button.

Finally, we close the form tags with </form>.

PHP Specifics

Let’s take a look at how we actually send the form contents to an email address.

<html>
<meta http-equiv=”refresh” content=”1.5;url=contact.html”>
<h1>
<?php
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$name = strip_tags(trim($_POST[“name”]));
$name = str_replace(array(“\r”,”\n”),array(” “,” “),$name);
$email = filter_var(trim($_POST[“email”]), FILTER_SANITIZE_EMAIL);
$subject = trim($_POST[“subject”]);
$message = trim($_POST[“message”]);
if ( empty($name) OR empty($subject) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo “Error, please try again.”;
exit;
}
$recipient = “email@domainname.com”;
$subject = “New Website Message From $name”;
$email_content = “Name: $name\n”;
$email_content .= “Email: $email\n\n”;
$email_content .= “Subject: $subject\n\n”;
$email_content .= “Message:\n$message\n”;
$email_headers = “From: $name <$email>”;
if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo “Thank You! I’ll read and then reply to your e-mail in a few days!”;
} else {
http_response_code(500);
echo “Oops! Something’s gone wrong, please try again.”;
}

} else {
http_response_code(403);
echo “There was a problem sending your email, please try again.”;
}

?>
</h1>
</html>

The first thing to notice is that the PHP file is actually wrapped in HTML tags. This is so that when the form is submitted we can display some validation messaging. I did this form this way as the client wanted the website to be easy to use for people with visual impairments. So you’ll notice the validation message is wrapped in <H1> tags. You should also notice that the page isn’t branded at all. It’s a blank page with just the validation messaging. These messages are displayed based on certain HTTP Response codes. An example:

http_response_code(500);
echo “Oops! Something’s gone wrong, please try again.”;
}

If there is an internal server error when submitting the form the browser will display “Oops! Something’s gone wrong, please try again.”

The page will then go back to the previous contact page using:

<meta http-equiv=”refresh” content=”1.5;url=contact.html”>

We went off on a bit of a tangent there. Let’s reign it back it.

The first thing the PHP script does is checks the action is POST. It then takes the fields and validates the contents of them to make sure they are of the correct types. For example, the e-mail address needs to be 100% valid, so we can apply some logic to check.

$email = filter_var(trim($_POST[“email”]), FILTER_SANITIZE_EMAIL);

FILTER_SANITIZE_EMAIL removes all of the illegal characters from the email address. Another example is remove the line breaks from the name field.

$name = str_replace(array(“\r”,”\n”),array(” “,” “),$name);

I won’t cover all of the validation, but if the fields fail the validation we can throw a message to the user.

if ( empty($name) OR empty($subject) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo “Error, please try again.”;

The next bit of the code takes all of the fields that have passed the validation checks and builds the email.

$recipient = “email@domainname.com”;
$subject = “New Website Message From $name”;
$email_content = “Name: $name\n”;
$email_content .= “Email: $email\n\n”;
$email_content .= “Subject: $subject\n\n”;
$email_content .= “Message:\n$message\n”;
$email_headers = “From: $name <$email>”;

And the penultimate step, we apply an if, else block to capture any problems when we send the email.

if (mail($recipient, $subject, $email_content, $email_headers)) {
http_response_code(200);
echo “Thank You! I’ll read and then reply to your e-mail in a few days!”;
} else {
http_response_code(500);
echo “Oops! Something’s gone wrong, please try again.”;
}

} else {
http_response_code(403);
echo “There was a problem sending your email, please try again.”;
}

Finally we close the <html> tags.

Summary

I really hope this PHP contact form tutorial has been useful. Please leave me a comment and let me know if you’ve used any of the guidance I’ve given you in this article. You can also check out some of my other tutorials.

3 Comments

  1. thanks for this. helped me create my first php form.

  2. great php form tutorial, thanks.

  3. Thanks a bunch for sharing this PHP contact form tutorial! saved my bacon

Leave a Comment

Your email address will not be published. Required fields are marked *

*