html form guide
  about

HTML contact form with captcha

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, spammers can misuse this contact form. So, it is necessary to secure your form so that spammers or hackers may not misuse it.

Click here to download the code explained in this article

How does the spammers/hackers exploit HTML forms

Usually spammers use html forms for two purposes:

a) For sending bulk unsolicited emails

If you are not validating your form fields before sending the emails, in your PHP script, then hackers can change your email headers info to send the bulk unsolicited emails. For example, hackers can place the following code in one of your form fields for this purpose:

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

This above code is simply altering the header info of your mail() function. It is adding another email address as a CC. It means that now this email will be sent to the above email address too (NewRecipient@anotherdomain.com). Spammers can send thousands of emails using this exploit. Your host will not be happy with this practice and will warn you as your site is sending the spam.
It may even ban your site.

The best way to prevent this spammer exploit is to validate all the form fields before using them to send the emails. The easiest way is to check for the presence of any "new line character" (\r\n) in all of your form fields. If you can screen your form fields for newline character, then this type of exploits could be avoided.

b) For Sending spam emails to your email address

Spammers also use the contact forms to send the spam emails to your email address. Spammers may use the software that can automatically fill your contact form and submit the form. This can be done in a cycle. It means software can send you thousands of junk emails on your email address by using your contact form. This will be eating your site bandwidth and server space. You will also require a lot of time to separate the real emails from the junk emails.

The software doing this are sometimes called "spam bots". The best way to avoid this condition is the use of "CAPTCHA" in your contact forms.

Adding Captcha to the form

html contact form : captcha

Spam bots are the software which can fill and send your contact form, automatically. The best way to block such software is to add Captcha to your form. Captcha is an image with some letters written on it. The user is required to see the word written on Captcha and write into a form field. If the word entered is wrong, the form will not be submitted. As Captcha is a smartly blurred image, the spammer's software cannot understand it. So the form cannot be auto-submitted. We can use some PHP code to add the Captcha to the contact form.

Use a free captcha script to add captcha to the form

There are various free PHP Captcha scripts available that can be used to protect your contact form. These scripts usually generate an image with some random characters. Visitors cannot send the form without writing these characters, correctly, in a form field. To correctly install the Captcha scripts on your website you need the basic understanding of HTML and PHP. Some of the scripts generate the Captcha image which is very difficult to read. So, before selecting any script, see the demo of the script.

Sample code

Here, we are going to discuss a sample captcha code that can be used to protect your contact form. The code uses some graphical functions of PHP to display the image. You also need to add a font to set the style of characters on the image.

This example consists of 3 files. First one is the HTML form which can be named as "contact_form_with_captcha.html". This will display your contact form with a captcha image. The PHP code that is responsible to display and validate the Captcha is present in the file namely "captcha_code_file.php". The third file will be the "html-contact-form-proc.php". This file will give you the error message and no email will be sent, if the captcha code entered by user is wrong. If the captcha code is correct, this file will send the email normally.

So let us see and discuss this sample code.

Code of "contact_form_with_captcha.html"

<HTML>
<HEAD><title>Contact Form</title></HEAD>
<BODY>
<form method="POST" name="contact_form" action="html-contact-form-proc.php">
Enter Name: <input type="text" name="name"><br>
Enter Message: <textarea name="message"></textarea><br>
<img src="captcha_code_file.php" /><br>
Enter captcha Code Here :<input id="6_letters_code" name="6_letters_code" type="text" ><br>
<input type="submit" value="Submit"><br>
</form>
</BODY>
</HTML>

Above code is very straight forward. This code will display a simple HTML contact form with two fields "name" and "message". After the "message" field there is an image tag. The source property of this image is set to our captcha script called "captcha_code.php".

Code of "captcha_code_file.php"

<?php
session_start();
$image_width = 120;
$image_height = 40;
$characters_on_image = 6;
$font = 'monofont.ttf';
$possible_letters = '23456789bcdfghjkmnpqrstvwxyz';

$code = '';


$i = 0;
while ($i < $characters_on_image) {
$code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
$i++;
}


$font_size = $image_height * 0.75;
$image = @imagecreate($image_width, $image_height);


/* setting the background, text and noise colours here */
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 20, 40, 100);
$image_noise_color = imagecolorallocate($image, 100, 120, 180);


/* generating the dots randomly in background */
for( $i=0; $i<($image_width*$image_height)/3; $i++ ) {
imagefilledellipse($image, mt_rand(0,$image_width), mt_rand(0,$image_height), 1, 1, $image_noise_color);
}


/* generating lines randomly in background of image */
for( $i=0; $i<($image_width*$image_height)/150; $i++ ) {
imageline($image, mt_rand(0,$image_width), mt_rand(0,$image_height), mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}


/* create a text box and add 6 letters code in it */
$textbox = imagettfbbox($font_size, 0, $font, $code);
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code);


/* Show captcha image in the page html page */
header('Content-Type: image/jpeg');// defining the image type to be shown in browser widow
imagejpeg($image);//showing the image
imagedestroy($image);//destroying the image instance
$_SESSION['6_letters_code'] = $code;
?>

Code explanation:

The above code is responsible for the creation of captcha image with the random 6 letters displayed on it. The first few lines of code are setting some important variables like the width of the image, height of the image and the number of characters.

$font = 'monofont.ttf';

This line is telling which font to use. Here we are using the font name "monofont". Remember that the font file must be placed in the same folder where this file is present. You can use any font you like. Just change the name here and place the new font file in the same folder. $possible_letters = '23456789bcdfghjkmnpqrstvwxyz';

This variable is holding all the characters that can appear on the captcha image.

$i = 0;
while ($i < $characters_on_image) {
   $code .= substr($possible_letters, mt_rand(0, strlen($possible_letters)-1), 1);
   $i++;
}

This code is generating a random 6 letters code that will be placed on the captcha image. This code is present in the variable "$code".

$image = @imagecreate($image_width, $image_height);
An instance of image is created by using the imagecreate() funtion of PHP.

/* setting the background, text and noise colours here */
$background_color = imagecolorallocate($image, 255, 255, 255);
$text_color = imagecolorallocate($image, 20, 40, 100);
$image_noise_color = imagecolorallocate($image, 100, 120, 180);

Here we are defining the colors of the captcha image. We are using the PHP's image functions to set the different color properties of the image.



/* generating the dots randomly in background */
for( $i=0; $i<($image_width*$image_height)/3; $i++ ) {
   imagefilledellipse($image, mt_rand(0,$image_width), mt_rand(0,$image_height), 1, 1, $image_noise_color);
}

This code is using the imagefilledellipse() function of PHP and filling the background of image with random dots.



/* generating lines randomly in background of image */
for( $i=0; $i<($image_width*$image_height)/150; $i++ ) {
    imageline($image, mt_rand(0,$image_width), mt_rand(0,$image_height), mt_rand(0,$image_width), mt_rand(0,$image_height), $image_noise_color);
}

This code is using the imageline() function of PHP to make the random lines in the background of captcha image.



/* create a text box and add 6 letters code in it */
$textbox = imagettfbbox($font_size, 0, $font, $code);
$x = ($image_width - $textbox[4])/2;
$y = ($image_height - $textbox[5])/2;
imagettftext($image, $font_size, 0, $x, $y, $text_color, $font , $code);

The above code is creating a graphical text box by using the width, height and font properties of image. Now this text box will contain the captcha image with the 6 letters code on it.



/* Show captcha image in the page html page */
header('Content-Type: image/jpeg');// defining the image type to be shown in browser widow
imagejpeg($image);//showing the image
imagedestroy($image);//destroying the image instance
$_SESSION['security_code'] = $code;

As we have now made our captca image, we just need to display it on the screen. We are using the imagejpeg() funtion to display the image on the screen. After this we are destroying the image by using the imagedestroy() function. Here we are storing the 6 letters code in a session variable called "6_letters_code". We shall use this variable to validate the user input later.

Code of "html-contact-form-proc.php"

The above two files were responsible for the creation and display of contact form and captcha image. When the user fills the form and enters the captcha code value and hits the submit button, user is taken to the "html-contact-form-proc.php" page. This page will validate the captcha security code. If it is wrong, it will display an error message and no email will be sent. If the code is correct, the email will be sent.

Here is the complete code:

<?php
session_start();
if( $_SESSION['6_letters_code'] == $_POST['6_letters_code'] && !empty($_SESSION['6_letters_code'] ) ) {
   $to = "RecipientEmail@domain.com";
   $email_subject = "This is the email subject";
   $name = $_POST['name'];
   $message = $_POST['message'];
   $email_body = "You have received a new messag from " . $name . ". Here is the message: " . $message;
   mail($to, $email_subject, $email_body);
   echo 'You entered the correct code. Your message is successfully emailed.';
} else {
echo "Sorry, you have provided an invalid security code. Please <a href='contact_form_with_captcha.html'>CLICK HERE</a> to try again.";
}
?>

First of all we have used the function session_start(). This is to tell that we are going to use the session variables in the script. Then comes the If condition. The value  of 6 characters captcha code was stored in the session variable namely "6_letters_code".

Here we are comparing this code with the value of the code entered by the user. If both values are same then we will get the name and message from the POST array and will email the message. If both values are not same, it means that code was not correctly entered. In this case the ELSE portion will be executed and an error message will be displayed.

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


  • Digg
  • del.icio.us
  • Netscape
  • Reddit
  • StumbleUpon
  • Technorati
  • YahooMyWeb


Related pages

 
  • Digg
  • del.icio.us
  • Netscape
  • Reddit
  • StumbleUpon
  • Technorati
  • YahooMyWeb
Email forms
  How to get email from html form submission

Email form using 'mailto'

Form to email using PHP

Email form with file attachment in PHP

Form mail scripts
  Form mail script selection guide

Perl based form mail

Contact Forms
  PHP based email contact form

Secure your HTML contact form using captcha
PHP Form
  PHP form validation script

PHP form tutorial: first steps

PHP form processing

PHP form 'GET'

PHP form 'POST'

Handling checkbox in PHP form processor

Handling select box in a PHP form

Using PHP_SELF in the action field of a form

How to submit a form using PHP

Creating a registration form using PHP

Making a login form using PHP

Creating a multi-page order form using PHP

Passing PHP form variables from one page to other

  Copyright © 2008 html-form-guide.com . All rights reserved.