How To Write A PHP Contact Form

Before we begin, it is probably best to start with a disclaimer:

The contact form that we will create here validates user input and minimizes the chance that it could be used improperly, such as for spam. Unfortunately, just about anything on the web can be ‘hacked’ by enterprising hackers. However, this form should thwart most attempts. (See below for more details regarding our release of this code sample, and additional ways to make it hacker proof.)

Alright, ready? Let’s begin. (Want to skip the tutorial? Download all files now.)

The A’s, B’s, and C’s of Contact Forms

A contact form is composed of two main pieces, the HTML which displays the form and the backend code which processes the form. In the code sample below, we’ve provided the HTML which would create a contact form containing a text area and two fields, one for an email address and the other for a name.

<form method="post" action="contact.php">
<input type="text" name="name">
<input type="text" name="email">
<textarea name="message"></textarea>
<input type="submit" name="submit" value="submit">
</form>

The code that processes this form will be a bit more complicated. After all, it needs to accomplish a few things such as:

  1. handling the user input and sending it to the server for validation
  2. making sure that all fields are filled in
  3. verifying that email addresses are valid
  4. preventing hackers from exploiting the form for spam
  5. serving error messages
  6. sending the details to you via email
  7. displaying a success message

We will handle each of the above items in turn. Let’s start with with the first item on the list: handling user input.

1. Handling User Input

To handle user input, you need to be able to (1) determine if the form was submitted, and (2) retrieve submitted values. Take a look at the code sample below:

<?php
if(isset($_POST['submit']))
{
    $name   = $_POST['name'];
    $email   = $_POST['email'];
    $message   = $_POST['message'];
}
?>

In this code sample, we check to see if the form was submitted by checking the value of the variable $_POST['submit']. Then, within the if statement, we retrieve the other form inputs and save them to the variables $name, $email, and $message.

Well, that was easy enough. Now we have to write code to ensure that users fill in all fields.

2. Dealing With Required Fields

To make sure that users have entered all required information, you can test each variable as show in the code sample below:

<?php
$error = "";
if(trim($name)=="" || trim($email)=="" || trim($message)=="")
{
    $error = "Oops! All fields are required."
}
?>

In this sample, we have used the PHP trim() function which removes all whitespace. Then we test to see whether or not each variable has a value. If not, the $error variable is set to the error message.

Now onto validating user email addresses. Click below to go to the next page.

 

Pages: 1 2 3

Tags: ,

25 Responses to “How To Write A PHP Contact Form”

  • On December 3, 2008 at 8:07 am,Velvet Blues wrote:

    One user asked about adding a drop down box (or select element) to the form. This could be easily done by adding a new element or replacing an existing element with the following sample code:

    <select name="gender">
    <option>female</option>
    <option>male</option>
    </select>

    Then simply modify the $POST variables at the top of the form, as well as the email message to include this variable.

    Be sure to edit the select options and name to something suitable for your form.

  • On December 3, 2008 at 2:04 pm,carl wrote:

    Thanks for the code, but how exactly should the other modifications be done? Can you be a little more specific? How do you ad the choics that will drop down?

  • On December 3, 2008 at 2:25 pm,Velvet Blues wrote:

    @Carl, you will need to go through 3 steps:

    1. Add that select element to the form HTML code. (ie. the HTML code that we’ve shown under the first subheading)

    2. Update the $POST variable. (See section 1: Handling User Input). Assuming that you had a select element like the sample above, with the name ‘gender’, your added code might look something like this:
    $gender = $_POST['gender'];

    3. Update the email message. As you will see, we used a single variable for the ‘message’. So we’ll need to combine the variables for your additional element to include that in the message. So you will need to add another line of code after the $gender and $message lines. The code might look something like:
    $message = $gender."\n".$message;

  • On December 3, 2008 at 7:06 pm,carl wrote:

    I have all that working, last question, and thanks for your help…..

    In the e-mail I receive from the form the data entered and selected by the user are included, but not the names of the fields they filled out. Example:

    Carl Martin
    carl@martin.com
    Test
    This is a test.

    SHOULD BE

    Name: Carl Martin
    E-mail: carl@martin.com
    Subject: Test
    Message: This is a test.

  • On December 3, 2008 at 7:13 pm,Velvet Blues wrote:

    To fix this, you’d just edit the variable. Using the example that I included in my last reply, you could achieve the following output:

    Gender: Male
    Message: Some message

    using this code:

    $message = " Gender: ".$gender."\n Message: ".$message;

    or, simpler:

    $message = " Gender: $gender \n Message: $message";

  • On December 3, 2008 at 7:33 pm,carl wrote:

    You have been a big help, all of these issues are now fixed. I am having an issue though. You spoke of another way to have the form send the email and I may need you to elaborate on that. I use Yahoo! for my hosting. For some reason, if I use my e-mail address as the address in the form then the mail is sent to me, if I use any other email address…NOTHING!

  • On December 3, 2008 at 7:40 pm,Velvet Blues wrote:

    Yahoo is one of those restrictive web hosts. You will need to consult their documentation, but I am almost positive that you have to (1) use an email address which is set up via Yahoo for your domain, and (2) set it up under the special email ‘PHP Mail Setup’ options, as a valid address from which mail can be ‘sent’…

    I haven’t done too much work on Yahoo hosting, so I probably can’t be of any additional help in this regard.

    Good luck!

  • On December 3, 2008 at 7:44 pm,carl wrote:

    Thanks, I will consult their documentation and their people. I am using the email thats registered and I have done the PHP setup, its just not working, I thought maybe you knew of a workaround. Thanks.

  • On December 6, 2008 at 11:22 pm,carl wrote:

    I truly appreciate this script and I have solved the Yahoo! Server issue. I have detailed this below.

    In order to get this script to work 100% perfectly with Yahoo! Servers you need to change only a single line of code. This is the original line you need to modify:

    $headers = “From: $name \n”;

    The modified version should be as follows:

    $headers = “From: \r\n”;

    The E-mail you actually receive will appear as being sent from Your Email address. To make this something else, Modify the code in this manner:

    $headers = “From: FROM NAME \r\n”;

    Thanks.

  • On December 6, 2008 at 11:23 pm,carl wrote:

    This is not showing up correctly in my post, email me and I will give you the correct data and you can add it, webmaster, thanks.

  • On December 8, 2008 at 5:11 am,carl wrote:

    i sent you an email with the proper code

  • On December 8, 2008 at 9:03 pm,Velvet Blues wrote:

    Thanks Carl, I have added the proper code to the end of the article.

  • On December 8, 2008 at 10:46 pm,carl wrote:

    Do you have any code samples lying around for a “Tell A Friend” script that behaves in the same manner as your contact form script?

  • On December 9, 2008 at 7:10 am,Velvet Blues wrote:

    Hi Carl, no I don’t have a “Tell A Friend” script that I can release. But there are likely tons of them floating around the internet. Google “tell a friend php script“, and you should retrieve some websites which have free samples available.

  • On December 9, 2008 at 4:50 pm,carl wrote:

    I did that, most of them do not work property, are cumbersome, or lack features. I love the contact form script and how it works in its own space, no extra windows, etc. Any idea what would have to be modified to make it send data like a refer a friend script? thanks.

  • On December 10, 2008 at 12:06 am,Velvet Blues wrote:

    Depending on what features you’d want, it will most likely be a bit more complex than this script.

    But the simplest possible implementation would be one where you just change the recipient email address and have it point to a user-supplied email address for their friend. And then you could have a standard message that is sent to all ‘friends’…

  • On March 20, 2009 at 5:38 pm,affiliate funnel wrote:

    Great post Velvet.

    Very simple and effective php form.

    Thanks

    Rob

  • On September 24, 2009 at 9:15 am,bita wrote:

    Very simple and effective php form.

    great write up

  • On December 4, 2010 at 6:32 am,webhostingruchi wrote:

    I’m using a local host. I tried and tested it but my yahoo account is not receiving anything.
    I changed the email address provided in sendmail.php to my own email but it seems like is not working on my side.
    What should I do?
    Please help.

  • On December 8, 2010 at 7:14 pm,Velvet Blues wrote:

    @webhostingruching: Perhaps your localhost does not have a working mail server. That is pretty common. What software are you using?

  • On December 22, 2010 at 11:02 pm,Dave wrote:

    I tried the code and I’m getting an error that says that eregi is deprecated. It’s also saying Notice: Undefined index: message in C:\wamp\www\temporary\contact.php on line 11 I’m seeing this on the localhost, my website doesn’t support php yet.

  • On December 23, 2010 at 12:53 am,David wrote:

    I tried using your script and I got an error saying that ergeli is depracated and undefined variable on line 11. I’m trying to append this to a site that i’m working on.

  • On June 28, 2011 at 10:58 pm,Malar wrote:

    Hi
    I am using this contact form .But Could you please let me know how to connect to the mail server so that ie sends a actuall email.

    Regards
    Malar

  • On November 11, 2011 at 12:45 pm,RAGE!!!!! wrote:

    I have to ask why you automatically assume people know where this sendmail stuff is, I am working with WAMP and I am a newbie but I am trying to crash course PHP. I completely ran the script without an error, but guess what? I have no idea how to actually get the email. Not even the first thing.

    Couldn’t you have at least said “Gee, for those who aren’t ZEUS at programming and aren’t born with inherent GODLIKE programming knowledge, there is this thing called sendmail and it has to be specially configured knowing quantum physics!” I am going to quit programming because of this halfway written crap and go clean cars, or maybe burn myself.. thanks a lot.

  • On November 15, 2011 at 3:55 pm,SEO Maryland wrote:

    As I am developing my site I needed to make a contact script for my page, and this is definitely a huge help! Thank you!

Trackbacks

Trackback URL for this entry:
http://www.velvetblues.com/web-development-blog/how-to-write-a-php-contact-form/trackback/

Leave a Reply

Want us to work on your project?

Contact us today for a quote. Click here to submit details regarding your project.

If you are making a general inquiry, send an email to info@velvetblues.com