Create Captcha Verification in PHP

December 16, 2012 // In: PHP, Web Design

Captcha is basically human verification code and it can be used at register, contact, and login or comments forms to secure your forms from spamming. Captcha usually contains an image containing some numeric or alphanumeric characters and you need to enter same characters in the given text box.
It’s pretty simple and easy to implement.

Create a function that will generate Captcha image and returns the generated text code printed on that image.

Next, define variables to generate random numbers of any fixed length and also set width, height for the captcha image. Let say length of numbers is 5, width = 110 and height =35

Create image using imagecreate function for captcha, define color using imagecolorallocate or imagecolorallocatealpha to set in the background of the image and apply that background color to the image using imagefill function.

Now, add some random characters on it. For this purpose, copy any font to working web folder and store the path of font to a variable. Also set font color and then generate characters to add on the image.

At the end return the generate characters for verification purposes. So the final code is

If you want to add some noise on the background of the captcha image or add random lines on the background then you just need to add little more.
You need to create color for lines and then use loop to create random lines. Put these line of code before Font Path.

Now the final code is

Here is the complete working demo of Captcha varification, Its absolutely free and you can use it in your projects.

Download Try it today for free!

jQuery Accordion Plugin by Sharp Coders
HTML5 Semantic Structure
  • JD

    Thank you so much this is great. I’ve been “searching” and studying how to “capcha” for more than 5 hours and mostly, everything, including the captcha.com site was a “clear as mud.” This was diffently easy to the max, if I can figure what to do with the file.

    1. Do I unzip in webpage DIR?

    2. Do I copy and past the code into a page?

    3. How do I connect this to require surfer to complete their registration into my site (which is what I need it for.)
    Well again… really thanks you very much!