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.

{ 128 comments… read them below or add one }

Steve (UK) December 3, 2011 at 4:11 am

Code tested, working fine with added attributes but when pasted into web page, value=” appears in lable/text areas! Have I perhaps overlooked something? At a loss, help much appreciated. See: http://www.pcworkplace.co.uk/email/main.php (works fine) ; http://www.pcworkplace.co.uk/ = value script in text areas!

Reply

Thomas December 13, 2011 at 8:44 am

This Form script is nice, but the email is not send out! I have already check with example code (http://www.html-form-guide.com/email-form/php-script-not-sending-email.html) and this is working withoit problem, just this form script here does not send emails.

Anyone can help?

Reply

Scott December 14, 2011 at 1:33 am

Looked ta a whole lot of captcha samples that claim to be simple and this is the only one that was.

Reply

Cory Doyle December 16, 2011 at 10:24 pm

Love this script, but I just keep getting captcha code does not match! How is this possible, even when I load the download untouched up to my hosting server I get the same thing over and over, any advice would be very helpful. Thanks

Reply

Ali December 22, 2011 at 6:10 pm

Was help full for me!
tanks dear

Reply

Harish December 23, 2011 at 10:59 am

captch images are dosnt display…please guide me

Reply

Saj December 27, 2011 at 4:45 pm

Hi,

This is my second attempt to get this form working, with the captcha, i don’t see the captcha image..? just see a broken image, where the image needs to be showing,, there is no instruction to edit any file for the captcha part of the form, if there is then its missing in the instructions..!

can anyone give me some help on this..?

Thanks
saj

Reply

Prasanth December 28, 2011 at 3:08 pm

most probably, you do not have ‘GD library’ on your web server. Request your hosting service/admin to install GD library for PHP.

Reply

Bear December 31, 2011 at 6:40 pm

I do have GD installed on the hosting server, but no captcha image appears.
As a starting place, I am dumping the sample files into my hosting root directory. PHP and GD are both installed. The form displays, but with out captcha image.
A little help would be much appreciated.

Reply

Bear December 31, 2011 at 6:44 pm

Oops…I was testing on the wrong webserver. Works great. Thanks so much for this page. Huge timesaver!

Regards,
Bear

Reply

ESS January 2, 2012 at 4:48 am

Any way to test the code using localhost? I have it working with the confirmation page showing, but no email is sent.

I’m using my personal email for the time being before making it live.
Also, the scenario I’d like to use is having the submission sent to a GMail address vs. one from my domain. Possible?
Thanks so much!

Reply

jrilken January 4, 2012 at 11:08 pm

I’m using the form to send an email but I’m having some trouble getting the character encoding just right. I need it to be in UTF-8 since i want Greek characters allowed…

Thank you,
jrilken

Reply

RonBott January 5, 2012 at 6:24 pm

Thanks very much, this works great! I do have a question on what the correct syntax would be if I wanted to pass the value of a drop down list, such as:

Red
Blue
Green

Can anybody help?

Reply

SATINDER January 8, 2012 at 8:00 pm

Hi All,

Can anyone help/advise me the correct step to be followed for using above mention code as
form.html–>captcha_code_file.php ?????????????

Reply

eric roo January 10, 2012 at 4:56 pm

I installed this on my server and the captcha image is not displaying.

We do have GD Library for PHP installed on the server.

What else would make the image fail to display?

My host provider is asking if there is a list of requirements for this somewhere…

Reply

ramin January 14, 2012 at 12:04 pm

Very helpful and informative post. Still a bit technical but it is not that hard to implement. Thanks again for such a useful post.

– ramin

Reply

John January 20, 2012 at 1:08 pm

Like the simplicity. However, like one or two others, when I run your sample with no modification other than changing my email address the captcha works fine but doesn’t appear to be sending an email!

Anybody offer a fix?

Reply

John January 20, 2012 at 3:25 pm

All OK…was using wrong ‘from’ domain.

Reply

Nathan January 21, 2012 at 5:26 am

I get the noise image when I use this, but there’s no text in it :\ Any idea what’s wrong?

IE: http://temp.go-for-english.com/contact-us/captcha_code_file/index.php?rand=1561009796

Reply

Dan Stramer January 23, 2012 at 9:12 am

Thank you very much for the code.
When I tested it on my server it worked fine, but when moving it to my clients server the captcha always says “wrong code” even when the letters/numbers are entered correctly.
what could be the reason?
This is the clients site with the captcha not working:
http://www.doctorporat.co.il/index.php

Thanks in advance,
Dan

Reply

Tim Karr November 19, 2011 at 6:55 am

Argh.. the blog stripped out all the code and just left the text. Sorry. But you get the idea, right?

Reply

Leave a Comment

Previous post:

Next post: