Bootstrap Contact Form

How to Create a Working Bootstrap Contact Form with PHP

Contact forms are one of the most common elements found on a web page, and they can be used to gather just about any type of information required from your users.

Fortunately, designing contact forms with Bootstrap is a breeze with all of the built-in classes available. But since Bootstrap is only a front-end framework, we need to introduce added functionality in order for to make the contact form functional.

In this step by step tutorial, we’re going to be creating a working Bootstrap contact form with PHP, a popular server-side language. Our contact form will also have built-in spam prevention and form validation.

The HTML Markup

The first thing we need to do when building the contact form is to setup the proper HTML structure with the appropriate Bootstrap classes. Although not required, we’re going to center the contact form using the classes col-md-6 col-md-offset-3  and I’m going to assume you’ve properly nested the form within a row and container.

To help us get started, we’ll use the following HTML markup and we’ll go through each block in more detail.

<form class="form-horizontal" role="form" method="post" action="index.php">
	<div class="form-group">
		<label for="name" class="col-sm-2 control-label">Name</label>
		<div class="col-sm-10">
			<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="">
		</div>
	</div>
	<div class="form-group">
		<label for="email" class="col-sm-2 control-label">Email</label>
		<div class="col-sm-10">
			<input type="email" class="form-control" id="email" name="email" placeholder="[email protected]" value="">
		</div>
	</div>
	<div class="form-group">
		<label for="message" class="col-sm-2 control-label">Message</label>
		<div class="col-sm-10">
			<textarea class="form-control" rows="4" name="message"></textarea>
		</div>
	</div>
	<div class="form-group">
		<label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>
		<div class="col-sm-10">
			<input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
		</div>
	</div>
	<div class="form-group">
		<div class="col-sm-10 col-sm-offset-2">
			<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
		</div>
	</div>
	<div class="form-group">
		<div class="col-sm-10 col-sm-offset-2">
			<! Will be used to display an alert to the user>
		</div>
	</div>
</form>

Using this code, you should have something that looks like this.

Bootstrap contact form

Initially, it looks like we’re using quite a bit of code but notice that a lot of it is repetitive. First, let’s break down the HTML markup.

<Form>

First, everything is contained inside our <form> tag which is used to declare a form requiring user’s input.  Within the form tag, there are a variety of attributes.

Method: There are two different form methods that can be used, get and post. If we use get, the form data is appended in the URL upon submission. For example, if we submitted the form with a name of “Chris”, the URL would show http://domain.com/?name=chris.

On the other hand, using the post method will send the form-data as an HTTP post transaction. Generally, the post method should be used for contact forms.

Role: Bootstrap added the role="form" attribute in order to help with accessibility. It’s good practice to add this in.

Action: The action attribute is used to indicate the location of the PHP script. In this case, we’ve included the script on the same page as our contact form. For the sake of this tutorial, we’ll just use index.php.

<Label>

Labels are used to specify what information should be entered in each of the inputs. The for attribute is used to associate the label with the input name. In our example above, we set our name label to for="name". This will then associate the label to the input type that has id="name". If you click on the label “Email”, notice that your cursor will now be activated on the email input.

<Input>

Now that we have our labels, we need to declare our inputs.

Input Type: There are several different kinds of input types and it’s important to specify the correct one, especially when it comes to mobile. If we select an “email” input type, the email keyboard will be displayed on mobile devices. If we select the “tel” input type, mobile users will be able to click on the telephone number and make a call on the spot.

In our contact form, we’ve used input types of text, email and submit. Notice that text area is not a type of input and rather its own HTML tag. Also note that you can specify the total amount of rows you want the text area to take up by default. In our example we used 4 rows.

Id: The id attribute allows you to provide a unique identity for your HTML element. As we just discussed, this comes in handy when associated the labels to your inputs.

Name: The name attribute is used to reference elements in a JavaScript, or to reference form data after a form is submitted. In our case, we’ll be using the name in conjunction with our PHP code.

Placeholder: Placeholders enable you to display text inside the form inputs, mainly for extra instructions. Notice that as soon as a user begins typing into the form inputs, the placeholder text disappears.

Value: The value attribute varies depending on the type of input. In the case of our text inputs, the value is used to define the initial input value of the form. We’ve left this blank for now but we’re going to be introducing PHP code. You’ll see why later on.

In the case of buttons, the value attribute is used to display the button text.

That just about covers all the HTML markup we need to get going. Before we start adding our PHP, let’s go over the Bootstrap classes we included in our markup.

Bootstrap Classes

As you can see, Bootstrap makes it extremely easy to style a form with minimal work. We just need to declare a few classes to get the needed styles.

First, we give our <form> tag a class of form-horizontal which will use Bootstrap’s predefined grid classes to align labels and groups of form controls in a horizontal layout. We then create a new <div> for each input area with with a class of form-group.

For each label, we use a class of control-label to properly style our labels. For this example, we also added a class of col-sm-2 so that our labels stack on top of the form inputs on smaller mobile devices. This makes it a lot easier to read the form on mobile devices.

Finally, we give each our inputs a class of form-control.

Introducing PHP

Now that all of the HTML markup is complete, we need to start adding our PHP markup.

Declaring The Variables

In our HTML markup, we assigned a name attribute to each of our inputs. We’re going to declare the following PHP variables to extract this data.

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$human = intval($_POST['human']);

Next, we need to declare additional variables required to send our email.

$from = 'Demo Contact Form'; 
$to = '[email protected]'; 
$subject = 'Message from Contact Demo ';

$body = "From: $name\n E-Mail: $email\n Message:\n $message";

Form Validation

Now that we have our basic variables in place, we need to introduce some validation to alert the user if there are any errors or missing fields.

For the name and message fields, we just need to check that a text has been entered. If no text has been entered, we’ll declare a new variable named “errName”.

if (!$_POST['name']) {
	$errName = 'Please enter your name';
}

The exclamation mark in PHP means ‘not’ so the code above translates to “If the name field is empty after posting, a variable of $errName is declared.

For our email field, we’ll also verify whether or not the email entered is a valid email using the following code.

if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
	$errEmail = 'Please enter a valid email address';
}

Finally, for the spam bot, we’ll verify that the number entered in the input field is equal to 5. If it’s not, we’ll declare another error variable.

if ($human !== 5) {
	$errHuman = 'Your anti-spam is incorrect';
}

Now that we have all our error variables declared, we want to display them under each form input when the form is submitted. For example, we’ll insert the following line of PHP under our name input.

<?php echo "<p class='text-danger'>$errName</p>";?>

Notice that we used the text-danger class to signify that there’s an error. With this line of code, the error will only be displayed if the user forgets to input their name.

With all our validation in place, here’s what the user will see if they submit an empty form.

Contact form errors

Using PHP to Store Initial Values

As we mentioned at the top of the tutorial, the value attribute of our text fields is used to set the initial value. If no value is set, the form will be empty each time we submit the form. This creates an issue if we submit a form with errors because even the fields that were filled out correctly will reset to empty. This becomes very annoying if we submit a form with an error and we have to re-enter all of our information.

Luckily, we can use PHP to store initial values. When doing so, the form inputs will not be reset if the form is submitted with errors. Instead, it sets the initial value to whatever text the user inputted before submitting the form.

This is accomplished using the following code.

value="<?php echo htmlspecialchars($_POST['name']); ?>">

This is the same code we used to declare our $name variable. Notice that we also added the htmlspecialchars on the posted values within the inputs in order to escape any malicious code that could be entered by the user.

Submitting the Form With PHP

We now have everything we need in order to submit the form. We start off with an if statement that checks whether the form was submitted. If it is, it will store all of the variables we identified above.

<?php
	if (isset($_POST["submit"])) {
		$name = $_POST['name'];
		$email = $_POST['email'];
		$message = $_POST['message'];
		$human = intval($_POST['human']);
		$from = 'Demo Contact Form'; 
		$to = '[email protected]'; 
		$subject = 'Message from Contact Demo ';
		
		$body = "From: $name\n E-Mail: $email\n Message:\n $message";

If the form is submitted, it will verify if there are any errors or missing information with the inputs.

// Check if name has been entered
if (!$_POST['name']) {
	$errName = 'Please enter your name';
}

// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
	$errEmail = 'Please enter a valid email address';
}

//Check if message has been entered
if (!$_POST['message']) {
	$errMessage = 'Please enter your message';
}
//Check if simple anti-bot test is correct
if ($human !== 5) {
	$errHuman = 'Your anti-spam is incorrect';
}

If no errors are present, we’ll submit the form.

// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
	if (mail ($to, $subject, $body, $from)) {
		$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
	} else {
		$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
	}
}

If the form submits successfully, we’ll display an alert using the alert alert-success class notifying the user that the form was submitted successfully. If the form doesn’t submit successfully, we’ll display an alert using the alert alert-danger class notifying the user that the form was not sent. Be sure to insert the following PHP code in the last form group that we initially left empty.

<?php echo $result; ?>

The Final PHP Code

With all of our variables and if statements in place, your PHP code should look like this.

<?php
	if (isset($_POST["submit"])) {
		$name = $_POST['name'];
		$email = $_POST['email'];
		$message = $_POST['message'];
		$human = intval($_POST['human']);
		$from = 'Demo Contact Form'; 
		$to = '[email protected]'; 
		$subject = 'Message from Contact Demo ';
		
		$body = "From: $name\n E-Mail: $email\n Message:\n $message";

		// Check if name has been entered
		if (!$_POST['name']) {
			$errName = 'Please enter your name';
		}
		
		// Check if email has been entered and is valid
		if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
			$errEmail = 'Please enter a valid email address';
		}
		
		//Check if message has been entered
		if (!$_POST['message']) {
			$errMessage = 'Please enter your message';
		}
		//Check if simple anti-bot test is correct
		if ($human !== 5) {
			$errHuman = 'Your anti-spam is incorrect';
		}

// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
	if (mail ($to, $subject, $body, $from)) {
		$result='<div class="alert alert-success">Thank You! I will be in touch</div>';
	} else {
		$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>';
	}
}
	}
?>

The Final HTML Code

Here’s what the final HTML code looks like with the added PHP included.

<form class="form-horizontal" role="form" method="post" action="index.php">
	<div class="form-group">
		<label for="name" class="col-sm-2 control-label">Name</label>
		<div class="col-sm-10">
			<input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
			<?php echo "<p class='text-danger'>$errName</p>";?>
		</div>
	</div>
	<div class="form-group">
		<label for="email" class="col-sm-2 control-label">Email</label>
		<div class="col-sm-10">
			<input type="email" class="form-control" id="email" name="email" placeholder="[email protected]" value="<?php echo htmlspecialchars($_POST['email']); ?>">
			<?php echo "<p class='text-danger'>$errEmail</p>";?>
		</div>
	</div>
	<div class="form-group">
		<label for="message" class="col-sm-2 control-label">Message</label>
		<div class="col-sm-10">
			<textarea class="form-control" rows="4" name="message"><?php echo htmlspecialchars($_POST['message']);?></textarea>
			<?php echo "<p class='text-danger'>$errMessage</p>";?>
		</div>
	</div>
	<div class="form-group">
		<label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>
		<div class="col-sm-10">
			<input type="text" class="form-control" id="human" name="human" placeholder="Your Answer">
			<?php echo "<p class='text-danger'>$errHuman</p>";?>
		</div>
	</div>
	<div class="form-group">
		<div class="col-sm-10 col-sm-offset-2">
			<input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary">
		</div>
	</div>
	<div class="form-group">
		<div class="col-sm-10 col-sm-offset-2">
			<?php echo $result; ?>	
		</div>
	</div>
</form> 

Download the Source Code

We’ve covered quite a bit of code and it was broken down into several different chunks. To view or download the entire source code, you can access it via our GitHub page.

Sharing is caring!

Pavel Malos

Creating Digital Experiences @ BootstrapBay