You are here: Home » All Posts » Contact Forms » HTML contact form with CAPTCHA

HTML contact form with CAPTCHA

in Contact Forms

Using a contact form on your website is very useful as it helps your web site visitors to communicate with you in an easy and simple way. But, there are spammers and hackers who are looking for exploitable web forms. It is essential to secure your form against all 'holes' that those hackers are searching for.

Note: You can make secure contact forms quickly with Simfatic Forms. Simfatic Forms helps you to make complete, feature rich forms and get it online quickly. Read more here.

How does the spammers/hackers exploit HTML forms?

Spammers exploit web forms for two purposes:

a) As a relay for sending bulk unsolicited emails

If you are not validating your form fields (on the serve side) before sending the emails, then hackers can alter your email headers to send the bulk unsolicited emails. (also known as email injection) For example, hackers can place the following code in one of your form fields and make your form processor script send an email to an unintended recipient:

sender@theirdomain.com%0ABcc:NewRecipient@anotherdomain.com

The code above is adding another email address to the CC list of the email. Spammers can send thousands of emails using this exploit. Your host will not be happy with this and may warn you or even ban your web site.

The best way to prevent this spammer exploit is to validate the fields used in the mail() function(fields like email, subject of the email, name etc). Check for the presence of any "new line" (\r\n) in those fields. The email form article contains sample code that does the same.

b) For Sending spam messages to you

There are programs known as 'spam-bots' that leech through the web pages looking for web forms. When found, those 'bots' just fills the fields with a spam message and submits. Eventually you will start getting many hundred submissions send by those spam bots and you will find it difficult to separate genuine submissions from spam messages.

The solution for this problem is to use a mechanism to identify human submitters from 'bots'. CAPTCHA is one of such tests.

Adding Captcha to the form

Captcha is an image with a code written on it. The website visitor is required to read the code on the image and enter the value in a text field. If the word entered is wrong, the form submission is not processed. As CAPTCHA is a smartly blurred image, the spam bot can't read it. So the form cannot be auto-submitted by a 'bot'.

The contact form with CAPTCHA

Here is the HTML code for the contact form:

<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<label for="name">Name: </label>
<input type="text" name="name"
value="<?php echo htmlentities($name) ?>">
<label for="email">Email: </label>
<input type="text" name="email"
value="<?php echo htmlentities($visitor_email) ?>">
<label for="message">Message:</label>
<textarea name="message" rows=8 cols=30
><?php echo htmlentities($user_message) ?></textarea>
<img src="captcha_code_file.php?rand=<?php echo rand(); ?>"
id="captchaimg" >
<label for="message">Enter the code above here :</label>
<input id="6_letters_code" name="6_letters_code" type="text">
<input type="submit" value="Submit" name="submit">
</form>

The HTML form above contains the fields for name, email and message. In addition, we have the CAPTCHA image. The <img> tag for the CAPTCHA image points to the script captcha_code_file.php. The PHP script in 'captcha_code_file.php' creates the image for the captcha and saves the code in a session variable named '6_letters_code'.

Validating the CAPTCHA

When the form is submitted, we compare the value in the session variable(6_letters_code) with the submitted CAPTCHA code( the value in the text field 6_letters_code). If the codes match, then we proceed with emailing the form submission. Else we display an error.

Here is the code that does the server side processing:

if(isset($_POST['submit']))
{
  if(empty($_SESSION['6_letters_code'] ) ||
    strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
  {
      //Note: the captcha code is compared case insensitively.
      //if you want case sensitive match, update the check above to
      // strcmp()
    $errors .= "\n The captcha code does not match!";
  }
  if(empty($errors))
  {
    //send the email
    $to = $your_email;
    $subject="New form submission";
    $from = $your_email;
    $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';
    $body = "A user  $name submitted the contact form:\n".
    "Name: $name\n".
    "Email: $visitor_email \n".
    "Message: \n ".
    "$user_message\n".
    "IP: $ip\n";
    $headers = "From: $from \r\n";
    $headers .= "Reply-To: $visitor_email \r\n";
    mail($to, $subject, $body,$headers);
    header('Location: thank-you.html');
  }
}

Customizing the CAPTCHA

The CAPTCHA script in the sample code download can be customized. If you open the script, you can see the first few lines of the code as shown below:

$image_width = 120;
$image_height = 40;
$characters_on_image = 6;
$font = './monofont.ttf';
//The characters that can be used in the CAPTCHA code.
//avoid confusing characters (l 1 and i for example)
$possible_letters = '23456789bcdfghjkmnpqrstvwxyz';
$random_dots = 0;
$random_lines = 20;
$captcha_text_color="0x142864";
$captcha_noise_color = "0x142864";

You can change the size of the CAPTCHA by changing $image_width & $image_height. The number of characters in the CAPTCHA can be changed by updating $characters_on_image. Similarly, the text color of the CAPTCHA can be customized by updating $captcha_text_color. The code adds some 'noise' in the image by adding random lines and dots. you can increase or decrease the noise. Please note that increasing the noise may make it difficult for your genuine visitors to read the code.

Download the code

Click here to download html-contact-form-captcha.zip

Reference

The above captcha code is based on the code developed by Simon Jarvis:
http://www.white-hat-web-design.co.uk/articles/php-captcha.php

See Some More Contact Form Code Downloads

The following pages contain some more contact forms that you can download and customize as required

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

No related posts.

{ 161 comments }

Darren August 16, 2011 at 11:36 am

Hi, I have been using this contact form for a while and it was working great, unfortunatly my host has disabled PHPMail on my server and I have to use a script with SMTP authentication. Is their anyway to adapt the script I have been using as I have the form looking exactly how I like it, and its been a great little form until my hosting company decided to drop support for PHPMail. Many thanks in advance to anyone who can help.

tobio August 28, 2011 at 2:27 am

you can Use the external email :D !! for example Yahoo or Google webmail :D

una August 26, 2011 at 3:25 pm

I tried the form on my local server but I got the following message.Does anyone know what this means?
Any help fixing this would be much appreciated. Thanks
Deprecated: Function eregi() is deprecated in C:\wamp\www\simple-contact-form-1-2\include\fgcontactform.php on line 548

Deprecated: Function split() is deprecated in C:\wamp\www\simple-contact-form-1-2\include\class.phpmailer.php on line 470

Andrew Townsend October 5, 2011 at 4:25 pm

This is because you have a newer version of php installed and they have changed the function to run regular expressions, if you search php net for eregi it will tell you the replacement cant remeber exactly that is just a quick name change, and do the same for the split function.
 
Regards
Andrew Townsend
Exclusive Web Systems

Sites Like Craigslist August 26, 2011 at 11:33 pm

Thanks for the useful advice and tips.
I am sure many of us, laymen would benefit from it.
 
 
Regards,
Jessica

Fiesta August 27, 2011 at 7:48 am

It’s working fine for me.
You’ve saved me hours of writing code.
Thank’s a lot you do a great job!

Fiesta August 27, 2011 at 10:49 am

Everything is working fine for me, except:
1. An email with nothing between @ and . eg: test@.com doesn’t post an error message.
2. When the message field is empty I dont get the error message.
How can be fix it? Thanks a lot.

Glen September 5, 2011 at 6:25 am

Hi,

I’m getting a ‘Validator’ is undefined error….. How can I clear this?

Regards,

Glen

Prasanth September 16, 2011 at 7:41 am

The javascript files are not include or is not uploaded

Justina Virgin September 8, 2011 at 5:17 am

The fact i prefer around your website is you often article immediate to the point details.

jithin September 8, 2011 at 3:24 pm

it’s gud !

Prashant Patil September 10, 2011 at 7:25 pm

Check this blog for the captcha image code using php:
http://wamp6.com/php/simple-validation-captcha-image-php/

Flossie Davis September 13, 2011 at 8:02 pm

I have been using a template to create my site.  I have a banner on all my pages.  I’m ready to create my contact.html page (in fact, it is all ready) I need to put a contact form on this page of my temple.  I don’t know where to place the code within the code view (Dreamweaver CS4) or where to add or put the contactcss or php code for the form to work.  I know I sound lost, because I am.  Please help

Prasanth September 16, 2011 at 8:00 am
office furniture workstations September 14, 2011 at 5:40 am

You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand. It seems too complicated and very broad for me. I am looking forward for your next post, I will try to get the hang of it!

Glen September 20, 2011 at 3:16 am

Hi,

I got it all working, but today when I went to my site the CAPTCHA image isn’t showing anymore. I haven’t changed anything….. What might have happened?

Glen

Glen September 21, 2011 at 2:29 am

Never mind, I recopied the captcha php file and it cleared the error. Not sure ehat happened for it to stuff up but it’s fixed.

But on another note, if I want to change the colour of the text in the image to white, which part do I change in the script?

Glen

Chris J. Popp September 21, 2011 at 9:44 pm

The script works great for CAPTCHA.. the problem however that I am having is that Name and Visitor’s Email does not come through on the sent email. Also, the name or email address is not passed to the headers so when I get the email it comes as being from something like 2611395.2864544@vux.bos.netsolhost.com
If I pull the <?php echo htmlentities($name) ?> and <?php echo htmlentities($visitor_email) ?> lines out and leave the values blank then I get the entries in the form email and the email will come from “Luke.Skywalker@vux.bos.netsolhost.com”.
I’ve tried both visitors_email and email for the address that the visitor enters with the same result.

Paul Markey September 21, 2011 at 11:40 pm

Hi

I have set up the contact me form and it keeps on coming up with invalid e-mail adress even though I know it is correct ??

Any ideas

Mo September 29, 2011 at 12:24 am

Well, I’ve got it uploaded to my host and the captcha works, and so does the Thank You page.. but I’m not receiving the emails. I changed the “$your_email =’yourname@your-website.com’;// <<=== update to your email address” line so that yourname@your-website.com is my address that I want it sent to. Any ideas? Thanks!

Berentank September 29, 2011 at 7:16 pm

I got the same problem here…
but has it to be the e-mail adress of the host, were the file is uploaded?
 
Thanks!
 
 

Kay October 1, 2011 at 5:12 pm

Interesting….i changed the email address where I wanted to go to my hotmail acct and it came thru. with a message that said it looked suspicious but it came thru. Is there anyway to get my server to not block it?

Kim October 1, 2011 at 1:00 pm

Having the same problem as Mo. I thought I was doing so good. We are almost there. Help please. Thanks

Mo – ”
Well, I’ve got it uploaded to my host and the captcha works, and so does the Thank You page.. but I’m not receiving the emails. I changed the “$your_email =’yourname@your-website.com’;// <<=== update to your email address” line so that yourname@your-website.com is my address that I want it sent to. Any ideas? Thanks!

Robert October 4, 2011 at 7:31 am

the problem is hotmail… 5 messages and block it.
i test with differents emails…
excuse my english,,, i speak spanish…

Shalom Tesciuba October 3, 2011 at 1:49 pm

Hi
Amazing stuff by the way, just trying to use on my holding pages, only one problem. Its all looking amazing, but when you press the submit button nothing happens it just refreshes.
 
What am i doing wrong! grrr

Elena October 6, 2011 at 7:31 pm

Hi,
I added the fields in the contact form and everything works.

But now I want to add 2 radio buttons, each with a yes and no.
How do I insert the radio buttons.
how do I create the control is active on yes so that form send, otherwise if the locks do not

Thanks!

thanks

Brent October 7, 2011 at 4:19 am

Great form I like it !
One quick question (I hope)
How would I setup the gen_validatorv31.js to check validation of a phone number?
 
Thanks Again,
 
Brent

Brent October 7, 2011 at 6:36 am

One last question if you have time.
How do I add a Cc or BCC to $your_email =’sample@gmail.com’;//
 
Thanks!
Brent
 

Comments on this entry are closed.

Previous post:

Next post: