4 Simple Steps to Create CAPTCHA Script in PHP

4 Simple Steps to Create CAPTCHA Script in PHP

This is simple and powerful CAPTCHA script, using this script I’m going to generate a random number and then creates an image. If the user submits the form with correct captcha value, then you can proceed with next statements like inserting data into the database or sending an email.

5 Steps to Add “No CAPTCHA reCAPTCHA” Using PHP

1. Create HTML Page with Basic HTML Markup

This is Baisc HTML Markup with simple form inside body section with name, email & captcha fields also a submit button. Save this file as index.php

2. Create captcha.php file to Generate Captcha (CAPTCHA Script in PHP)

Create a new php file and save it as captcha.php, then open php block and write session_start PHP function.

Then generate a random number using rand function and store this in the session variable. Below is the example code.

Above code generates only four digits number, if you want to generate captcha code with numbers and also combined with strings then use this below code.

You can use any above code to generate captcha as per your requirement.

Define sizes of captcha image and also font size of captcha.

Then define content type of cpatcha.php file to image/jpeg

Create captcha image with defined sizes and set background color, you can use this below code.

Set captcha text color, you can play with these values and settle with your desired colors.

Create captcha image from generated captcha string. And then output this image in browser. We are generating captcha text from a specific font, you can use font whatever you like.

3. Display this captcha code in our Form

In our first steps, I’ve added a simple form with captcha input field. To display captcha code use image tag and in the source attribute add captcha.php file. After adding your code should look like this below code.

4. Check the captcha code after form submission

Next we need to verify the submitted captcha code is correct or not. We can do this by checking the submitted captcha value with session value, if both values matches then submitted captcha value is true and if both values are not matching then the submitted value is not correct.

User session_start PHP function. And check if POST superglobal is set and not empty. If the condition is true then check submitted captcha code & code stored in session superglobal. Below is the code.

Complete Code

If you have any problem in assembling above pieces of code, you can use this below complete code.

If you have any problem in using this code, let me know through the comment form below.

how to create captcha in php
Vivek Vengala

Vivek Vengala is a Online Entrepreneur, Web Developer from Hyderabad India.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: