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

Be Sociable, Share!
Bob James February 7, 2012 at 8:23 am

Thank you for this powerful script but is there a possibility to force the form to send UTF-8 content… My page is UTF-8 already but still I cant manage to let the form send with this encoding… My visitors write in Arabic and in Hebrew and everytime we get such an email on Outlook or thunderbird we keep fixing the encoding manually… I know that this is not a big deal but for a 50 years old and none technical people like my bosses it is…. Thank you

ejay February 8, 2012 at 12:02 pm

@Daniel, perhaps you’ve got to session_start();

Paul Devine February 10, 2012 at 8:10 pm

Is there a way to add another field such as telephone number?

Thanks

Jairo February 11, 2012 at 5:12 pm

not appear the captcha code, im a begenir dunno how fix it?? can you help me??
Thanks

http://vipbeachhouse.com/VIPbeachHouse.com/html-contact-form.php

Brett February 13, 2012 at 1:36 am

I have been trying to add recaptcha to a review form offered by citricle but it does not seem to work. As a novice at this, is there a source of information I can go to in order to learn how to do this integration?

Dan February 14, 2012 at 4:57 pm

Anyone know how to successfully implement a drop down menu in this scenario. I can get them working but I can’t them to display on seperate lines in the email body or remember the settings should a user miss type the captcha. Any ideas?

Real Assignment Writing February 21, 2012 at 11:53 am

Post very nicely written, and it contains useful facts. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement. Thanks for sharing with us

KeyDog February 15, 2012 at 11:30 pm

The solution to the UTF-8 encoding issues for the emails being sent:

After:
$headers .= “Reply-To: $visitor_email \r\n”;
Add:
$headers.=”Content-Type: text/plain;\n\t charset=\”utf-8\”\n”;

Boris February 21, 2012 at 10:23 am

Form isn’t working for me… I also get following codes showing in fields:

Name:
Email:
Message:

After I click on button submit I get this error:
Not Found
The requested URL /< was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

What could be wrong?

Sheri February 22, 2012 at 7:44 pm

I installed the content form to my website, but when I test it, it just keeps asking me more anti-spam questions and doesn’t send me to the “thank you” page. Yahoo is my server, and I notice that on my original contact form after “method-post” there is another field called “action-http://us.1.p.webhosting.yahoo.com/forms?login=xxx”

Should I add this action field to the form or is there something else keeping it from working?

http://www.katiebuglove.com/contact/contactform.php

Any help at all is appreciated!

Una March 15, 2012 at 3:18 pm

i have same problem, keeps failing the anti spam and asking for more questions. How did you fix this?

Sheri February 23, 2012 at 1:08 am

Okay, I got it to work and send mail but I’m not getting a re-direct to my “thank you” page. I’m still working on the style sheet so don’t take points off for the appearance!

Help is appreciated!

Sheri February 23, 2012 at 8:39 pm

I have everything working now except for the re-direct to my “thank you” page.

Also, this code:
<input type='text' class='spmhidip' name='GetSpamTrapInputName(); ?>’ /
was adding a text box without a header and it wouldn’t align with the rest of the form, so I removed it. Probably shouldn’t have. What is it for. Is it essential?

Prasanth March 2, 2012 at 4:02 pm

The css file is not uploaded/linked properly

Sheri March 7, 2012 at 2:57 pm

I’m using an internal css.

Prasanth March 7, 2012 at 3:42 pm

That’s fine; but you have to use the css file in the download as well. The style for the form is in that css.

Jamaica Taxi Tours February 27, 2012 at 5:05 am

This forms really works, i used it on 2 of my website

arubalisa February 29, 2012 at 4:06 pm

Thank you so much! Found this post by searching “html email form with captcha” on google. Being self taught, this is something I have been “trying” to do for 2 years and was successful within a matter of a half hour! Easy peesey!

Jeffrey March 5, 2012 at 8:25 am

I like the simplicity and how this is clean and tidy for a script, its so easy to understand, except everytime I try to get it to just display the thank you message on the same page as the form instead of a thankyou.html page it crashes, I think it would be nice to just refresh the page with the thank you message above the form just like the errors but I can’t seem to get any code to work, it just crashes, I have tried to echo but that didn’t work, something about the header(location tag has me baffled… any ideas would be great, I love this form.

Falmouth Travel Guide March 6, 2012 at 3:10 am

Hello, can this form use in my word press post

Aaron March 7, 2012 at 5:56 am

Can anyone tell me the code for a drop down in this contact form. Thanks in advance.

Aurélien March 9, 2012 at 9:23 am

Thank you very much for your work and the time you spent on it!
Your form just works fine !
Great Job!

V March 16, 2012 at 6:23 pm

i might be very stupid but i can’t make it work on my website :S
i placed the script with the form on the place where it should stand.
uploaded the php document and all the other files to the server.
but it didn’t show the captcha.

kapil March 19, 2012 at 10:12 am

Thanks for this contact forms. Really great work it helps for website designers like me.

thanks again

vinny March 21, 2012 at 9:30 pm

nice scripts

Comments on this entry are closed.

Previous post:

Next post: