How To Create A Contact Form With PHP?

Contact forms are one of the most integral parts of any website. They are what give it a humane touch. Almost every blog or website has one. But you'd be surprised at how only a few people actually know how to make a contact form. Since they're so important, we figured it'd be a nice idea to teach beginners how to create them, instead of relying on any third-part to do the work for them. We previously shared a post on creating a responsive contact form using HTML and CSS. Today, we'll continue that tutorial, and teach you how to actually make a contact form work.
If you haven't gone through the first tutorial, then I'd strongly recommend you to do so.  That tutorial covered everything from markup to structure to styling a contact form. In this tutorial, we'll only cover the programming part, and we'll use PHP to make our contact actually work (accept inputs and send them to an email address). So if you know how to write the markup for a contact form, you're ready to move on!

Powering a contact form with PHP

Before we jump into the PHP, I'd like you to take a look at our basic structure first.

<form>
  <div id="form-inner">
    <label for="name">Name:</label>
    <input class="input" id="name" placeholder="Enter your name here" type="text" />
    <label for="email">Email:</label>
    <input class="input" id="email" placeholder="Enter a valid email address" type="email" />
    <label for="message">Message:</label>
    <textarea class="input textarea" id="message" placeholder="Type in your message here"></textarea>
    <input class="button" type="reset" value=" Reset" />
    <input class="button" type="submit" value="Submit" />
  </div>
</form>

First of all, we need to add an action to our form tag. So first, you need replace the top line that says "<form>", with;

<form method="post" action="index.php">

The method="post" attribute provides a way of extracting values from the input fields of a contact form using PHP. The action="index.php" attribute specifies the PHP file this data should be sent to. The PHP script for sending an email needs to be stored on a file. It can be a separate file, or the same HTML file that contains your form's markup. For this tutorial, we'll keep the script in the same file, so index.php should be the name of your file with the contact form.

Note: In order to add a PHP script to an HTML file, you need to change the file's extension from .html to .php. The HTML markup would work just fine even after the change. But keep in mind that you won't be able to run PHP files on your computer without having the PHP software installed on your computer. Typically, this software is only found on servers, but you can download it for free - it's a small software. You can either download it separately, or download a packaged software that contains other server software (recommended). Examples of such software include WAMP, XAMP, ZendServer, and so on. All are free to use, and readily available for download.

So now that we've set up the stage for our PHP script, it's time to actually start writing one.

Variables

First, we need to extract the data from the contact form, and store it in a variable (or container). Here's the script;

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    $from = 'From: MBT Contact';
    $to = 'contact@mybloggertricks.com';
    $subject = 'Contact Message';

    $body = "Sender name : $name\n Sender E-Mail : $email\n Message : $message";
?>

The script starts with the opening <?php tag, and ends with the closing ?> tag. The first three lines capture and store the values generated from the contact form. Note how we're using $_POST variables for data extraction. This is thanks to the method="post" attribute we used in our form tag.

The next three lines specify the source of the email generated, the destination email address, and the subject line. Notice the source says "MBT Contact". We can use the sender's name or email address here, but you probably want to know which message is coming to you via the contact form, and which is coming directly to your inbox.

The last line puts all the information received from the contact form into a single string for convenience.

Mail function

We're now ready to send our message. Take a look at the following script;

<?php
    if ($_POST['submit']) {
        if (mail ($to, $subject, $body, $from)) {
            echo '<p>Thank you for your feedback! We'll be in touch shortly</p>';
        } else {
            echo '<p>Something went wrong. Please try again!</p>';
        }
    }
?>

The first line (after the opening tag) contains a condition that checks whether the variable $_POST['submit'] has been created. This will only happen if a user clicks on the submit button. So in other words, the message won't be sent unless the user hits the Send button. Sounds reasonable?

Alright. Next, we have our mail () function inside another condition. This condition checks for the successful execution of the mail () function. If successful, a success message is displayed. Otherwise, the user is asked to try again.

Here's the final script;

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    $from = 'From: MBT Contact';
    $to = 'contact@mybloggertricks.com';
    $subject = 'Contact Message';
    $body = "Sender name : $name\n Sender E-Mail : $email\n Message : $message";

    if ($_POST['submit']) {
        if (mail ($to, $subject, $body, $from)) {
            echo '<p>Thank you for your feedback! We'll be in touch shortly</p>';
        } else {
            echo '<p>Something went wrong. Please try again!</p>';
        }
    }
?>

Did this tutorial help you? Leave us your feedback in the comments section below. Cheers :)

If you don't want to get yourself into Serious Technical Trouble while editing your Blog Template then just sit back and relax and let us do the Job for you at a fairly reasonable cost. Submit your order details by Clicking Here »

2 comments

PLEASE NOTE:
We have Zero Tolerance to Spam. Chessy Comments and Comments with 'Links' will be deleted immediately upon our review.