How to Create an HTML/PHP Contact Form – Processing Form Data with PHP

Gears - image by Alvaro Heinzen

In the previous tutorial – creating HTML PHP contact form – we successfully created a basic layout for the contact form. By the way, I’ve also added 2 screencasts to the post for those of you guys who really prefer video content to textual. So, if you wish to watch instead of read, you can do it. In other words you can choose now which way to go. Alternatively, you can both watch and read (or the other way around) just for better understanding. By the way, I’d really appreciate if you subscribe to our YouTube channel and like our videos. 🙂 Now let’s make our contact form actually do something. First off, it’s a good idea to understand how it works.

Under the hood

So, what happens after a user hits the “Submit” button of our contact form?

1)Let’s go step-by-step. The user fills in the form and hits the button:

2) Remember we assigned the action and method attributes to the form tag? Well, here’s where they come into play. The action attribute specifies that all the form data should be submitted to the send-mail.php file. Method="POST" means that all the values will be stored in an associative array called $_POST

3) Now let’s illustrate the data that the server receives from the contact form (screenshot below)

Here’s how the $_POST array looks like after we send the message. Anything familiar? Hell yeah!
The keys of the array (on the left side) match the names we specified in our html contact form. Each key contains a value – and the value is the data that was submitted (values on the right side of the array).
Now let’s move on and process this data with the send-mail.php file

Creating PHP file for the contact form

Below is the complete code of the send-mail.php file

<?php
    $mail_to = 'webdesy@gmail.com'; // specify your email here

    // Assigning data from the $_POST array to variables
    $name = $_POST['sender_name'];
    $mail_from = $_POST['sender_email'];
    $phone = $_POST['sender_phone'];
    $message = $_POST['sender_message'];

    // Construct email subject
    $subject = 'www.mysite.com Message from visitor ' . $name;

    // Construct email body
    $body_message = 'From: ' . $name . "\r\n";
    $body_message .= 'E-mail: ' . $mail_from . "\r\n";
    $body_message .= 'Phone: ' . $phone . "\r\n";
    $body_message .= 'Message: ' . $message;

    // Construct email headers
    $headers = 'From: ' . $mail_from . "\r\n";
    $headers .= 'Reply-To: ' . $mail_from . "\r\n";

    $mail_sent = mail($mail_to, $subject, $body_message, $headers);

    if ($mail_sent == true){ ?>
        <script language="javascript" type="text/javascript">
        alert('Thank you for the message. We will contact you shortly.');
        window.location = 'contact-form.html';
        </script>
    <?php } else { ?>
    <script language="javascript" type="text/javascript">
        alert('Message not sent. Please, notify the site administrator admin@admin.com');
        window.location = 'contact-form.html';
    </script>
    <?php
    }
?>

Now let’s dig it a bit. First, we create the $mail_to variable, which basically stores the recipient’s email address. Next, we create 4 variables ($name, $mail_from, $phone, $message) and assign the corresponding data from the $_POST array to each of them.

$subject = 'www.mysite.com Message from visitor ' . $name;

The email’s subject consists of two parts: static text – www.mysite.com Message from visitor, and the $name variable, which is basically the visitor’s name. So when you receive this email its subject would be “www.mysite.com Message from visitor John Smith”

In the following two lines, we construct the headers of our email message. The “From” parameter indicates the origin of the email, “Reply-to” is the visitor’s email address.

Now goes the line of code, which actually sends the email message. Notice that we assign the mail() function to the $mail_sent variable. What for? When the mail() function is executed, the server will respond either with True or False, depending on the fact if the email was sent or not. With the help of the PHP “if ... else” statement, we can assign a specific action if the email succeeded or not. And that’s exactly what we do next:

    if ($mail_sent == true){ ?>
        <script language="javascript" type="text/javascript">
        alert('Thank you for the message. We will contact you shortly.');
        window.location = 'contact-form.html';
        </script>
    <?php } else { ?>
    <script language="javascript" type="text/javascript">
        alert('Message not sent. Please, notify site administrator admin@admin.com');
        window.location = 'contact-form.html';
    </script>
    <?php
    }

If the $mail_sent variable is equal to “true”, then we echo a success javascript message, otherwise – echo a fail message.

We got to the end of the second tutorial, which I hope was helpful for you. If you got any questions or ideas, don’t hesitate to leave a comment and we will try to assist you. You can download both files for the first tutorial and current one at the following link HTML PHP Contact Form Files – Part 2

And if you feel like watching a movie now, here you go 🙂

About The Author

Tobias

I'm keen on developing websites. Any sentence that has HTML/CSS/PHP in it, will most likely generate interest for me )

  • It’s really need that you display the ready-to-use code right off the bet, because it’ll allow people to just copy and use it  where they want too without much of a hassle if any. Thanks for you generosity. 

    • Tobias Wagner

       You’re always welcome ) Stay tuned for more Contact Form posts. I’ll cover some really good stuff there

  • can you help me? i try to create auto popup form in lightbox and the form send to my email (using send_email.php).thank you

    • Could you give me more details as for what exactly you’re trying to achieve? Please give me answers to the following questions so that I can better understand what you’d like to do:

      1. what do you call ‘auto popup’. Give me a link to see a similar functionality to what you want to make.
      2. what script does your send_email.php file have?

      Please let me know asap.

  • evilzone

    how do i place anti spam box with image in this form

  • lraccajr

    When i click the send button i get the message saying the mail sent, yes i have the correct email in the php script but i do not get the test email. I am using xxamp on a windows 7 pc . could this be it?

    • That’s because you’re testing it on your locally (on your PC). You need to upload it to real life server (test remotely). It’ll work in that case (provided that your code is correct).

  • winfield

    What are some reasons the javascript code would send alert that message was not sent? Thanks for the tutorial.

    • I’m not sure that i’m following. Please elaborate on what you mean.

  • Jon Fuller

    I cannot get the form to send the email to me, although it does present me with a thank you message and no errors. It is on a live server and still does not work

    • Please email me both your html and php files. I’ll take a looksie

      • Jon Fuller

        See I am unsure if it is my code or my hoster :S

  • Petar Bajic

    Hi Kenneth,

    I would like to add a subscribe checkbox ( ) to the form….Do you know the way to connect it with the send-mail.php file so that it returns the info, via the email, weather a visitor is interested to subscribe to a newsletter or not? I think it has to be done through one of this two php paragraphs:

    // Assigning data from the $_POST array to variables
    $name = $_POST[‘sender_name’];
    $mail_from = $_POST[‘sender_email’];
    $phone = $_POST[‘sender_phone’];
    $message = $_POST[‘sender_message’];

    // Construct email subject
    $subject = ‘Message from visitor ‘ . $name;

    // Construct email body
    $body_message = ‘From: ‘ . $name . “rn”;
    $body_message .= ‘E-mail: ‘ . $mail_from . “rn”;
    $body_message .= ‘Phone: ‘ . $phone . “rn”;
    $body_message .= ‘Message: ‘ . $message;

    Cheers!
    Petar

  • Petar Bajic

    Hi Kenneth,

    I forgot to ask you in a last message for the instructions on how to install yahoo mail on a local host…

    cheers,
    Petar

  • Afolabi Mayowa

    i could not get my email sent i am getting erron on this code line “$mail_sent = mail($mail_to, $subject, $body_message, $headers);”

    • Thanks for your question, Afolabi. What exactly does the error message say?

  • Rajko Raspovic

    hi,
    i downloaded both files and using DW i put them on server(just to test it). but mail is not working :S (i changed mail address in php file so that one is good for sure). any ideas?

  • Alanoud Alosaimi

    Hi Ken ,
    I have one problem and that is you are not tell us how you link PHP file with HTML file ?

    • Thanks for your comment, Alanoud. As a matter of fact, you can see how to connect your HTML and PHP files in this post (previous episode of the series) – http://webdesy.com/creating-html-php-contact-form/

      In a nutshell, you specify your PHP file name in the very beginning of your form section that you have in your HTML file. Here’s how it looks in my case:

      That means the HTML file that contains the form will be sending its data to a PHP file called send-mail.php

      Hope it helps. Let me know if you need any help 🙂

  • Apurva

    i could not get my email sent i am getting erron on this code line “$mail_sent = mail($mail_to, $subject, $body_message, $headers);”

  • Apurva

    i could not get my email sent i am getting erron on this code line “$mail_sent = mail($mail_to, $subject, $body_message, $headers);”

    The error i get is

    failed to connect to mailserver at “localhost” port 2525 verify your smtp & smtp_port.

    I have hosted this files (contact.html & contact.php) on my server and my server has php 5.0 version still the mail does not go

    please help me to sort out this error.

  • Jesse

    What purpose does “window.location = ‘contact-form.html’;” serve in the JavaScript alerts?

  • Dimi Dekeyser

    Hi Vitaliy
    I have used your code and all fine but when I am on my website and submit the form I just get an indication that it has not been sent …. no reason why etc … how can I find the root cause ?

    Thx and brgrds

  • Azad

    Dear
    i have past above code, i am gating mail but mail is empty. please help.

    like…………….
    From:
    E-mail:
    Phone:
    Message:

  • Arijit

    gmail not supported. mails are not send ..