December 12, 2013

Widgets

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 :)


About Author:

Qasim Zaib is a passionate blogger who enjoys writing articles on Technology, Make Money Online and Blogging niche. He is our Gold Star Contributor and co-author of all blogs under our network.

Follow him @ Twitter | Facebook

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 »

10 comments : Post Yours! Read Comment Policy ▼
PLEASE NOTE:
We have Zero Tolerance to Spam. Chessy Comments and Comments with Links will be deleted immediately upon our review.

  1. Superb widget bro keep rocking
    www.mybloggerwidgets.com/

    ReplyDelete
  2. Replies
    1. May that is because your server or hosting provider does not allow sending emails. You can use third party smtp servers...!
      Online Diary

      Delete
  3. Thanks for such a informative articles hats off
    www.careerjobpk.com

    ReplyDelete
  4. i had tried and it is working exactly as u described thanks brother techftmusic we are also working like you brother help us.

    ReplyDelete
  5. thanks for sharing such a informative article. You explained it very well and in such a way that it seems very easy to understand.
    Emrithacks

    ReplyDelete
  6. Liked | Shared | Bookmarked | Superb Article
    thanks for sharing such a informative article. You explained it very well and in such a way that it seems very easy to understand.
    Blogger Fun Tricks

    ReplyDelete
  7. Great for help for beginner.. i have tried with that.. its works. - www.vnronline.com

    ReplyDelete

Support Us

We have educated thousands of bloggers online and made several people Make a living Online. If our Tutorials have really helped you a little, then kindly show your love by using the badge below:-

Blogger Widgets

or try a Beautiful Banner

Widgets

 
  • MBT Icons and buttons

    Icons and Buttons

    Our resources have been successfully downloaded over 10K times and found almost every where. Get yours!

  • choosing webhost for a blog

    Why HostGator?

    Learn Why we chose HostGator as our Web Host and find discount coupons to kick start your blog today!

  • SEO Settings for blogger

    ALL IN ONE SEO PACK 2012

    Learn every single SEO tip that will boost your blog's ranking and organic traffic. We got them all!

  • Blogger widgets and plugins

    Visit MBT's Blogger LAB

    Why not take a tour of all great Blogger widgets published so far? You Name it we have it!

  • become a six figure blogger!

    Become a SIX FIGURE BLOGGER

    Learn what it takes to become a successful entrepreneur and build a living online!

About The Author

Hi! I am Mohammad, a certified SEO Consultant, Pro Blogger, Computer Engineer and an addicted Web Developer. STC Network was founded in 2008 and it is currently the country's first registered company of Professional Bloggers. Read More..

Recipes

SEO Affiliate Marketing Social Media

Make Money Online Web hosting

Blogging Tips Web Designing

Plugins and Widgets Blogging Ethics

Subscribe

Recent Comments

Popular Series

Powered by:

My Blogger Tricks © 2013. All Rights Reserved | Contact |