PHP TutorialsWeb Developer

Create a Custom Contact Form for Website with PHP and HTML

Written by:

Having a custom contact form for your website these days is critical. Everyone wants to know where they can get in touch with a developer or a company. And there is not more convenient way than to have a simple and custom contact form for your website. The best part is that is can be done quick and easy with a little bit of PHP, HTML, and CSS.

What this custom contact form will do

  • display a nice, simple contact form
  • take the user’s info (name, email, and message)
  • send an email to your email address

Create a Custom Contact Form

The whole purpose of our custom contact form is to be simple but to the point. Usually you just want people to get the minimal options they need to send the email. If it is simpler, then people are more likely to use it. Also the less info they need to enter, the more likely they are to use it.

After the user enter’s their info and the message into the simple form, we can do some simple form validation to process the info they provided. Then use a few lines of PHP code to email their message to a your desired email address.

Download the free source code for this tutorial: Download Source Code

HTML Code for the Contact Form

We are going to create a simple HTML form to collect a simple information fro the user. Let’s get a name, email address, and then the message itself. Then of course a button to submit the form. Simple enough.

<div class="form"><form action="contact.php" method="POST">

            <div class="">
                <input type="text" name="name" value="" placeholder="Your name" />
            </div>

            <div class="">
                <input type="text" name="email" value="" placeholder="Your email address" />
            </div>

            <div class="">
                <textarea name="message" value="" placeholder="Your message for us?"></textarea>
            </div>

            <div class="">
                <input type="submit" name="sendBtn" value="Send Message" />
            </div>

        </form></div>

Basic setup for the HTML form

So we are creating our HTML form that will submit the form data using the POST method. This basically means that the info the user enters on the form will be passed to our backend for our processing. Usually, when you are letting user’s submit data to you web app, you should be using the POST method.

<form action="contact.php" method="POST">

For a contact form, you for sure do NOT want to use the GET method. That would pass the form data in the URL. Which is not pretty for lots of information, or even private information.

Using the form element, we specify the action attribute to be “contact.php”. This is telling our HTML form to submit all of our data to the contact.php script. Which in this case, is the same file that hold the custom contact form itself.

Then later down the HTML code, after all of the form elements of course, we close out of the form using the </form> tag. Nice and simple.

Create each of the HTML form elements

Once the form itself was created, we can create each of the individual form elements. We will create different form elements to let the user enter in their information like their name, email, and custom message.

Check this out:  Create a website redirect with php headers

We can use the input tag to create the name and email text boxes. Both of these elements are setup the same. We must specify the type attribute of “text” to turn it into a text box. Then give it a name so we can actually get the POST form data with our PHP code.

<input type="text" name="name" value="" placeholder="Your name" />

I like using the placeholder attribute to give the text box a little bit of flare. Specifying the placeholder tells the HTML form element to have some text displayed in it by default. Then when the user clicks into the box and starts to type anything, the placeholder text will disappear. I like to think it adds to a better user experience. People like movement on pages!

You can learn more about the placeholder attribute on W3 schools.

<textarea name="message" value="" placeholder="Your message for us?"></textarea>

After we create the name and email text boxes, we also create a textarea for the contact message. Textarea elements are similar to a text box, but they are bigger and let people type in more lines of text. Unlike an input element, a textarea requires you to give it an open tag and close tag. Just like many other HTML elements.

<input type="submit" name="sendBtn" value="Send Message" />

Lastly in our HTML form, we need to create a button for the user to click in order to actually submit the form data to our PHP script. Similar to creating text boxes, HTML buttons are created with the input tag. Simply give it a type of submit and change the name to something that makes sense, like “submitBtn”.

For buttons, there is no need to give a placeholder attribute since we will have a value actually set. The user will not be changing the displayed text of any buttons. Just specify a value of what you want to button to say to the user. In this case, I am going with “Send Message”.

Retrieve the HTML form data from POST in PHP

Now that we have the custom HTML form setup to collect the inputs from the user, we can code out the PHP script to process the HTML form data and email it off. Once the user clicks on the submit button, it will submit all of the form data to our script.

NOTE: Be sure to have all the PHP code to process the form input data ABOVE the HTML code for the form itself. This will allow you to process the form data and display any messages to the user you need. Like error messages.

<?php

    // check to see if the submit button was clicked
    if (isset($_POST['sendBtn'])){

        // get the POST data from the user
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];

        // make sure all the form data was provided
        if ($name && $email && $message){
            // create the email headers to send
            $to_email = 'demo@heytuts.com';
            $subject = 'New Message from: '.$name;
            $headers = "From: ".$email;

            // send the message to the desired contact email
            if (mail($to_email, $subject, $message, $headers)){
                $display_message = 'Your message has been sent. You should hear back in a few hours!';
            }
            else
                $display_message = 'An error occurred while sending your email. Please try again, or email '.$to_email.' directly.';
        }
        else
            $display_message = 'Please fill out the entire form to send us a message.';
    }

?>

First off, we are checking to see if the contact form was actually submitted. Since after all, it doesn’t make much sense trying to process data that was not submitted. Right?

Check this out:  How to Change Your YouTube Email Address

Using the isset function, we just check to see if the $_POST[‘sendBtn’] element exists. If the function returns a true value, then the form was actually submitted. If not, then the user was likely just loading the page the first time.

Get the form data via $_POST

// get the POST data from the user
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

Next, we can get all of the HTML form data using the $_POST variable. This variable will contain all of the data that was submitted with the form. PHP will create an associative array that you can get each and every bit of data you want out of it.

Easy form validation for the contact form

if ($name && $email && $message){ .....

After we have the form data, use a quick if statement to see if it was all provided. If it was then move on. If not then I create the $display_variable. By creating this variable, we can use it to easily display the different error or success messages out to the user.

Email the contact message with PHP

Once we have done out little form validation, we can actually email off the message to the address you set. Best part, is it only takes a few lines of PHP code.

Create the email headers

First we create some new variables to store the mail headers. To send any email, you will need the address to send it to and a subject of course. The $to_email variable will store the email address that will actually receive the contact message. So this is the one you will want to be sure to set to your personal or business email address. And make sure it is correct!

 $to_email = 'demo@heytuts.com';
 $subject = 'New Message from: '.$name;
 $headers = "From: ".$email;

Then to send emails with the php mail function, you have to specify at least one basic email header. Specifically the “From” header. Notice the first letter is capitalized. This is very important to have that capital “F”. If you don’t, your mail header is not actually set and therefore will not actually send the email.

Check this out:  Add a favicon to your Website | best size, best format

Send the email with PHP

Once the mail headers are set in some easy to access variables, we can use the mail function to send the email.

if (mail($to_email, $subject, $message, $headers)){
                $display_message = 'Your message has been sent. You should hear back in a few hours!';
            }
            else
                $display_message = 'An error occurred while sending your email. Please try again, or email '.$to_email.' directly.';

By placing the mail function inside of an if statement, you will be able to tell if the mail function was successful in sending our email. If the function returns a true value (aka it was successful), then we set the $display_message to a good success message. If the mail function returns a false value, we set the $display_message to an accurate error message.

Don’t forget to display your error messages!

After the rest of the PHP script is done that handles the email action, don’t forget about displaying the status messages out to the user. I usually prefer to display the status messages directly above the form itself.

<?php
    if (isset($display_message))
        echo '<p>'.$display_message.'</p>';
?>

Much like when we determine if the form was actually submitted, you can use the isset function to check if $display_message variable was created. If the variable exists (aka it “is set”) then display it is some visually pleasing way. I’ll just put it into a paragraph tag. If the $display_message is not set, then we do nothing. Simple.

Voila! Custom Contact Form!

Your custom contact form is done. So load it up and give it a whirl. Make sure it works!

Download the free source code for this tutorial: Download Source Code

Improve on this Custom Contact Form

After your custom contact form is fully functional and sending contact messages to your account, you can take it a step further and turn those emails into stylish HTML emails using a simple PHP script.

And if you are hosting your website on a local web server, or just using a localhost web server, then you can configure that server to send the emails. Using the SendMail application and XAMPP, you can setup your localhost web server to send those emails for your. Without getting any error messages of course 🙂

So get into the ever growing email trend, and create some super sweet contact forms that send custom emails directly to your own email address. Happy coding!

Leave a Reply

%d bloggers like this: