How To Write A PHP Contact Form

3. Validating Email Addresses

If you receive a message from your contact form, you want to make sure that your visitors have submitted a valid email address so that you can respond to them. So you need some sort of function which checks to see if the email has the correct form. All email addresses for example have an @ sign, a period, and a domain ending or tld.

Now we’re not going to go into the details of how each piece of this function works, but here is code below.

function validEmail($email)
{
    return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb |bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd |cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj |dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb |gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr |ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki |km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md |mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my |mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe |pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc |sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg |th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc |ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i"
            ,$email));
}

To check whether an email address is valid, we simply use this function on any submitted address. Now onto the problem of spam.

4. Dealing With Spam

As we mentioned in a previous article, hackers can exploit a contact form and use it to send messages to other than the desired recipient/s. One of the ways that they do this is by entering special characters which allow them to take control of the form. So our email function needs to prevent these special characters from being entered. The function in the code sample below does just this:

function checkForSpam($fields){
    $spam = false;
    for ($i=0;$i<count($fields);$i++){
        if (eregi("%0A",$fields[$i]) || eregi("%0D",$fields[$i]) || eregi("\r",$fields[$i]) || eregi("\n",$fields[$i])){
            $spam = true;
        }
    }
    return $spam;
}

As you can see, if it finds a possible spam attach, it returns the boolean value true. You will see exactly how we use this function when we put everything all together. But for now, lets move on to error messages.

5. Displaying Error Messages

Displaying any error messages is simple. We’ve already introduced the $error variable. To display any errors to users, we can just use echo like this:

<?php
echo $error;
?>

And it is likely that this statement would be placed directly above the form element.

When users enter all required fields and there are no error messages, we want to be able to send the info via email to a recipient.

6. Sending The Message

To send the message, we will take advantage of the PHP mail() function. There is another popular way to send mail, but to keep this tutorial simple, we’ll only focus on one method here.

The mail function only requires three parameters: recipient email, message subject, and message. However, we also like to supply additional headers. Headers help to ensure that the message is not flagged as spam and contain information such as the sender details, the type of message (text or html), and additional information about the system sending the message.

Take a look at the complete code sample below.

$priority = 3;
$php_version = phpversion();
$headers = "From: $name <$email>\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\n";
$headers .= "X-Priority: $priority\n";
$headers .= "X-Mailer: PHP $php_version\n";
$subject = "Message from contact form";
$to_email = recipient@example.com
mail($to_email, $subject, $message, $headers);

Almost done! All we have left to do is to replace the form with a success message upon successful submission.

 

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