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:

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">

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(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!";

    //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 ".
    "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_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


The above captcha code is based on the code developed by Simon Jarvis:

See Some More Contact Form Code Downloads

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

Be Sociable, Share!
Gabriel October 7, 2011 at 4:22 pm

How can i format to this form?

melissa October 15, 2011 at 4:44 pm

Thanks i am now able to create my forms, i really appreciate your site

Cindy October 15, 2011 at 5:00 pm

How can i add images to my form? How can i make certain input be limited like on my form i asked for phone number i want to make sure the maximum digit is 10 how can i do this?

Sam October 25, 2011 at 2:27 pm

Testing out the contact form sending forms to my own email address, after a couple of successes, it started going to junk mail and warning me it may not be genuine. can you help with this matter please.

john December 6, 2011 at 6:38 am

By setting the maxlength in HTML

0161-Jon October 25, 2011 at 5:08 pm

script looks great thanks. The captcha image isn’t displaying though, have I to change a path somewhere as I cannot see where this could be? All I get is a broken image symbol.

Prasanth October 29, 2011 at 3:20 pm

The captcha image is generated on the fly. Copy the captcha image link and past in your browser’s address bar. it will show the error message that is causing the problem

dataxploit October 27, 2011 at 12:48 pm

good post,,,,hope 2 some more

Shady Aggrey October 27, 2011 at 3:04 pm

Thanks alot. The captcha was very healpful and worked very well for my website

Amber November 2, 2011 at 11:09 pm

AMAZING! Love it! I’ve been looking for days for something like this. I’ve customized it with CSS a bit and placed it into a website I have.

saba November 4, 2011 at 1:33 pm

Even if I type in incorrect captcha it still sends the form. what can be the issue

Azhar November 20, 2011 at 9:30 am

saba. use your ability of work for a while and setup a programming intermediate level code. using if statement. not understood.

use , if(code is wrong) {
do this
} else {
do something else

hope now you learned it :) nice but little tricky question :

Joe November 6, 2011 at 9:09 pm

I was hoping someone could help me with my contact/CAPTCHA that I am trying to figure out. I have followed the instructions and believe everything is done correctly (uploaded the files as directed and filled in proper info), or so I thought. There are some punctuation that shows up in front of the form that should not be there and captcha doesn’t even show up. The site is

Joe November 6, 2011 at 9:10 pm

also… when I just delete the punctuation it messes the entire form up. not sure what to do.

Amber November 12, 2011 at 12:18 am

Great code!
However there is one thing, the submissions go to my junk inbox instead of my actual inbox. Is that to do with my email junk folder set up or is there something I can change in php?

Dani Dudovick November 19, 2011 at 1:13 am

Where exactly is “javascript: refreshCaptcha();” function??? Can’t find in “Scripts/gen_validator31.js” or anywhere else in download for that matter.
Pls help.
thx in advance,

freelance web designer kerala November 22, 2011 at 11:28 am

Great work….thanks………..

Robert Sharp November 23, 2011 at 9:08 am

This comes from using a html editor without knowing the underlying html.

If you look at your page source code,
You see the beginnings of your table.

; ; ?>'

The issue begins just after LAST QUOTE first line. You have a –> end of comment ling which is not shown.
The next line starts out with a ; semicolon then the hiddne field and at the other stray characters.

Simply edit the form fields and then you would be done.


JT Hutten November 25, 2011 at 10:28 am

Thank you so much… very helpful. Jedidiah

chhabindra November 26, 2011 at 4:11 am

Thank you

Serque November 27, 2011 at 2:03 pm

CAPTCHA can bypassed by
1000 captchas for only 1$ !

Karl Dallas November 30, 2011 at 2:14 pm

I assume I can’t use this form in a WordPress.Com or WordPress.Org site. If not, do you know how I can add a Captcha form to WordPress.Com? I know how to do it in WP.Org.

jeff December 1, 2011 at 6:37 am

Is this code compatible with IIS? Thanks!

Stewie December 3, 2011 at 1:06 am

Great form, got it working in no time. Exactly what I was looking for, Captcha authentication works a treat against Spam.

Comments on this entry are closed.

Previous post:

Next post: