Adding a Captcha Field to the Form

In this tutorial, we will add a Captcha field to our registration form. Captcha fields are important to make sure that a human and not a bot is registering for an account on your website.

Before we begin...

If you have not been following along with the form tutorials, you can either complete the tutorials or copy and paste the following code. So far in the tutorials, we have created a form in HTML and a process_form.php file to process the form and input the data into a database.

The form code (index.php):



The php code (process_form.php):



Downloading the Captcha files...

I use Securimage to generate the images for the Captcha. It is an open-source FREE PHP Captcha script and is very easy to add into your website.

Go to the following link and download either the 3.0.1 zip version or the 3.2RC2 zip version. For this tutorial, I am using the 3.0.1 version.

The HTML Code...

Now that we have the Captcha images installed and stored on the server, let's write the code to make them visible on our form.
  • On our form, in between the Selection List and the Submit button, we are going to add the code for our Captcha image.
  • First, we need to display the image. We do that by using the IMG SRC html tag and linking it to securimage_show.php in the folder that we copied onto the server.
  • We also need to add an input field for the user to enter the letters displayed in the image. We set the name of this field to Captcha_code.
The code for the HTML page:



Copy the Code: (The entire code for our form - Index.php)



Making Sure the Text Matches the Image...

Finally, we are going to edit the process_form.php file to make sure that the input in the text field matches the text on the Captcha image.

  • We have to include the securimage.php file from the downloaded Captcha files on the server.
  • We need to create a variable that invokes a new securimage object.
  • We write the code to check if the input matches the image.


The PHP Code:



Copy the code: (Process_form.php - full code including Captcha additions)



Our form now has a working captcha to prevent bots from signing up on our website.

And this is what it looks like...



Thanks for following along. Leave a post if you have any questions or topics that you would like a blog post on.

Comments