PHP Enquiry Form Using ReCAPTCHA

Introduction

Image of Recaptcha FormIf you have previously followed my tutorial on creating a simple PHP enquiry form then you will know that I introduced a very simple 'Maths Captcha' that asks the user to add two numbers together and enter them into a form field in order for the form to be actioned. This captcha method is pretty easily circumvented by sophisticated 'spambots' so I thought I would develop it further using a captcha plug-in called ReCAPTCHA.

ReCAPTCHA is available as a free download and it asks the person wanting to submit the form to write two words displayed in an image. The text is warped and disguised to make it hard to crack by spammers who want to send you those herbal viagra e-mails you don't want.

Using ReCAPTCHA is fairly straight forward but I find the instructions on their website do not cover all the bases you need to make the form from scratch and implement the captcha script. So I have written this step-by-step guide to help out.

Downloading ReCAPTCHA

First of all you need to visit the ReCAPTCHA website at www.recaptcha.net and sign up for an account. When you sign up the site offers you some information. It is absolutely essential that you open your favourite plain text editor (such as notepad) and make yourself a copy of this information. Of particular interest are the 'public' and 'private' keys. Copy and paste these into your editor and squirrel them away for use later. The site will also give you a zipped folder to download. Make sure you download this and save that for later as well.

Setting up your enquiry form.

Create yourself a page called something like 'contact.php'. For the rest of this tutorial, that is what I will refer to this as the Contact page. Please note that all of the pages in this tutorial must be created with a '.php' file extension for it to work. Next you will need to create your enquiry form. I am going to keep mine very simple but you can expand on what I have done here. My form will collect a name, e-mail address and have a text area for the user to type their enquiry. The code will look something like this;

<form action="mailer.php" id="contact" method="post">
<label>Name*</label>
<input name="name" type="text" size="30" id="name">
<label>E-mail*</label>
<input name="email" type="text" size="29" id="email">
<textarea name="enquiry" cols="50" rows="5" id="enquiry">Please type your enquiry here.</textarea>
<input type="submit" name="Submit" value="Submit" id="Submit">
</form>

You can style your form using simple CSS to make it look how you want but I won't cover that in this tutorial.

You will notice that the contact form has an 'action' that directs it towards a page called 'mailer.php'. This is probably as good a time as any to create a blank page and call it 'mailer'. Once again, you must use a '.php' file extension for this to work. I will refer to this page as the Mailer page for the rest of this tutorial.

Making the captcha appear in your form

First of all you will need to unpack the zipped file you downloaded from the ReCAPTCHA website. There will be a few files in there but the only one you need is the file called 'recaptchalib.php'. All you need to do with this file is to save it into the root folder of your website.

Still on your Contact page, you need to add the following code to your form just before the 'Submit' button;

<?php require_once('recaptchalib.php');
$publickey = "XXXXXXXXXXXXXXXXXXXXXX"; // you got this from the signup page
echo recaptcha_get_html($publickey);?>

Then you will need to copy and paste the 'Public Key' into the space indicated in the code. Remember that you copied the 'Public Key' into a text editor earlier in the tutorial. Once you have done this, try viewing the page in your browser to make sure that the Captcha form is there. NB: If you are developing your site locally then you will need to be running a local server such as WAMP for this to work. If the page is live on the web and you have PHP available to you then you should see the box.

Making the Mailer page

Open up the Mailer page that you created earlier and copy and paste the following code into it;

<?php
require_once('recaptchalib.php');
$privatekey = "XXXXXXXXXXXXXXXXXXXXXX";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if(!$resp->is_valid) {
header("location:error.php");
die();
}
?>

NB: The 'eagle-eyed' amongst you may have noticed that I have changed some of the code provided by ReCAPTCHA. The reason for this will become aparent later!

Next you should copy and paste the 'Private Key' you have in your text editor into the space indicated by the red 'X's.

Still on the Mailer page we are going to create the code that actually processes the e-mail and sends it to you. To process the basic form we created earlier we will use the following code (I have included all the code in mailer.php to avoid confusion);

<?php
require_once('recaptchalib.php');
$privatekey = "XXXXXXXXXXXXXXXXXXXXXX";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if(!$resp->is_valid) {
header("location:error.php");
die();
}
//these are the form results
$name = $_POST['name'];
$email = $_POST['email'];
$enquiry = $_POST['enquiry'];
$formsub = $_POST['Submit'];

if($formsub){

//this creates the body of the mail message
$mailMessage = "The message is: Hi XXXX. You have a message from the website\n\n";
$mailMessage .= "Name:" .$name."\n\n";
$mailMessage .= "E-Mail:" .$email."\n\n";
$mailMessage .= "Enquiry:" .$enquiry."\n\n";
$header = "From:you@yourdomain.com\r\n";
$header .= "Reply-To: you@yourdomain.com\r\n";
$header .= "Return-Path: you@yourdomain.com\r\n";
mail('you@yourdomain.com', 'Website Enquiry', $mailMessage,$header);

header("location:thanks.php");
exit;

}
?>

In the form processing part of the script you should change the details in red to suit your situation. For example replace the four 'X's with the recipient's name and the e-mail addresses with the correct ones for your purposes.

You might also notice that the results of the form on the Contact page are 'posted' into the PHP script. If you decide that you want more fields in your contact form then you will need to add these in the same format and also add them into the part of the script that 'creates the body of the mail message'. I will leave you to get your head round that though.

Making your 'Error' and 'Thanks' pages

I said I would come back to the reason I have changed the ReCAPTCHA script slightly. This is because the error that is shown to users with the basic script is not user-friendly and we want to be nice to our users! It simply displays a plain HTML message with no direction as to what to do next.

My suggestion is to save two copies of your Contact page, one called 'error.php' and one called 'thanks.php'. These will be known as Error page and Thanks page from now on. The reason I say to make them the same as the Contact page is so that users can have another go at sending their enquiry should something go wrong or if they have a second enquiry to make.

On the Error and Thanks pages you will need to create a message to the user either explaining that they have failed the Captcha test or thanking them for their enquiry. I would suggest placing these messages under the contact form on each page (so after the closing </form> tag as shown below);

</form>
<div class="message">Thanks for the message. I will be in touch soon</div>

You may want to style the text in the message tag using CSS. I tend to make mine big and red so that they stand out like so;

.message {
font-size: 14px;
color: #F00;
font-weight: bold;
}

That is about it. Upload all your pages. If you have followed my instructions closely then your Contact page should display the Captcha and success or failure when entering the two words required to send the form will result in redirection to the correct page with the correct message and a successful action will e-mail the details straight to you.

There are a couple more things that I think I should cover here based on my experience with ReCAPTCHA.

Changing the look of ReCAPTCHA

It is possible to restyle the captcha box to match your website. All you need is to place this javascript between the head tags of your page;

<script type= "text/javascript">
var RecaptchaOptions = {
theme: 'clean'
};
</script>

And then you are free to restyle the look of the ReCAPTCHA box using the following CSS;

.recaptchatable .recaptcha_image_cell, #recaptcha_table {
background-color:#fff !important; //reCaptcha widget background color
}
#recaptcha_table {
border-color: #fff !important; //reCaptcha widget border color
}
#recaptcha_response_field {
border-color: #000 !important; //Text input field border color
background-color:#fff !important; //Text input field background color
}

I'm not going to go in to how to do this here. If you don't understand this then you need to go right back to the basics!

ReCAPTCHA With Clean LookThere are some further options for styling. Where you can see the style in the javascript is set to 'clean' (see esample on the left) you could also try red, white, blackglass or custom. NB: If you style your captcha on the Contact page then you must also do the same with your Error and Thanks pages.

ReCAPTCHA and Internet Explorer issues

Yes, good old IE can have some grumbles when you use ReCAPTCHA as I found out in a very frustrating afternoon! If it looks like IE is failing to load half of your page when you use ReCAPTCHA then look at your other javascript. I know that ReCAPTCHA conflicts with Lightbox2 in IE and it may well conflict with other scripts as well.

All I did to overcome this was to remove all other instances of javascript from the page. Searching forums for other alternatives proved fairly fruitless I'm afraid so that may well be the only answer so keep your Contact page as scaled down as you can. If anyone else has a better solution to this then let me know.

Conclusion

Well, that is about it for this tutorial. Hopefully I have covered everything you need here to create a secure enquiry form for your customers whilst preventing your inbox from creaking under a deluge of spam.

If you would like to see ReCAPTCHA used in this way then click the 'Contact Me' button at the top of this page and send me a message.

Advertisements If you would like to advertise on Corrosive Online then get in touch through my Contact Page for details.
Join The Mailing List
    If you have found anything on this site useful or entertaining or you have enjoyed one of my Online Web Design Lessons then I would love you to make a donation. Use the Paypal button below to make a donation.