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.

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.

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

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”.

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.

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.

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.

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.

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.

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

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

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.

The Final PHP Code

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

The Final HTML Code

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

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.

Christopher Gimmer

Christopher is an entrepreneur & the co-founder of BootstrapBay. He helps web designers, developers and entrepreneurs utilize the power of Bootstrap. Connect with him on Twitter.