Building a Basic PHP Contact Form

August 31, 2014

Goal: to create a simplistic yet functional contact form using PHP

Tools Used: MAMP/LAMP, sublime text 3, google chrome

Building the HTML Form

In order to accomplish this task, you need to be able to execute php files in your internet browser. Usually this is accomplished by installing a MyApache/MySQL/PHP environment on your system and saving files to this localhost. For more information visit the official MAMP website.

MAMP actually stands for My Apache, MySQL and PHP, the three core technologies that the package contains.

This project will consist of two parts: one main "index.php" file (which is home to the form itself) and one helper file "mailform.php" (which handles the extraction of data from the form and sends the email).

First, create a new php file in the text editor of your choice (I prefer Sublime Text 3) and save it as "index.php" in a folder called "Contact Form" on your Desktop.

Let's first create the general HTML structure and then build the form:

<!DOCTYPE html>
<html lang="en">
	<title>Contact Form</title>
	<form action="mailform.php" method="POST" role="form">
		<h2>Contact Form</h2>
		<label for="name">Your Name</label>
		<input type="text" name="contact_name" placeholder="Your Name">
		<label for="email">Your Email</label>
		<input type="email" name="contact_email" placeholder="Your Email">
		<label for="message">Message</label>
		<textarea name="contact_message" rows="10" cols="40" placeholder="Type Message Here"></textarea>
		<input type="hidden" name="check-submission" value="contact">
		<input type="submit" value="Send"/>

A few notes:

  1. The form uses method="POST" to send its contents to the "mailform.php" file.
  2. The action="mailform.php" parameter directs the form to the mailer script. In the current example, "mailform.php" lives in the same directory as "index.php". If, say, you were to keep all of your helper scripts in a folder called Helpers within the parent folder Contact Form, you would need to change this to action="Helpers/mailform.php".
  3. role="form" is an optional parameter that helps mobile devices and screen-readers to identify page content.
  4. Use for="blah" with labels to "associate" them with an input field. The name of the input field should match the label's for parameter.
  5. Use <br> to force a quick line break or two between fields.
  6. Use the type=" " parameter based on the type of data you expect to receive. For example, by including type="email", we inform the script that we expect the user to include an @ symbol.
  7. Use a hidden input field (here named "check-submission") to ensure that the user has actually submitted the form (more on this later).

Notice how I've named each of the three inputs? The reason why I chose to prepend each with "contact_" is so that I don't get confused between the type of input I expect and the name of the field itself.

Receiving Data and Sending Mail

Next, we create our "mailform.php" file and handle the data. Be sure to replace the recipient email placeholder with your own:

// check for form submission using the hidden input field
	if (!isset($_POST['check-submission']) || $_POST['check-submission'] != 'contact') {
	    header('Location: index.php'); exit;
// get the posted data
	$name = $_POST['contact_name'];
	$email = $_POST['contact_email'];
	$message = $_POST['contact_message'];

// construct the email headers	
	$headers = "From: $email\r\n"; 
	$headers .= "Reply-To: $email\r\n";
	$subject = "Contact Form Submission";

// write email body
	$body  = "Name: $name\n";
	$body .= "Email Address: $email\n";
	$body .= "Message:\n\n $message";

// define recipient
	$to = "";

// send mail
	mail($to, $subject, $body, $headers);

// send the user back to the form
	header("Location: index.php"); exit;	


The first section of the code checks to see whether the variable $POST_['check-submission'] has been created and is equal in value to the string 'contact'. If true, the script continues; if false, the user is redirected back to the form.

When would this condition ever fail? If the user attempted to navigate directly to the "mailform.php" file. In this case, the hidden input field would not have been passed via POST and therefore $POST_['check-submission'] would not be set.

Notice that we use the dot operator (.=) to append strings to $body variable. Without the dot operator, we would overwrite the message content, instead of adding to it. We also add a few \ns (newline entities) to break content up.

That's it! Open the "index.php" file in your MAMP localhost environment and give it a try.

Note: this is NOT intended to be a secure or elegant way to send email. There are no precautions to check for valid (and safe) inputs or to prompt the user to fill out blank fields.

Positive that you've copied everything correctly, but still not receiving mail? Check your spam folder- you may find that messages are auto-trashed by your mail client.


Embedding Raw HTML using highlight.js

While highlight.js usually auto-detects code snippets, you will need to escape < and > yourself. I used Accessify's copy/paste tool here.

Escape Sequences

Confused about \r and \n? Read more here.