Generate Captcha Code Image With Form Validation - PHP

  • 26-07-2022
  • 1327
  • PHP
  • Haresh Chauhan

If you want to create your own captcha code image with the help of the GD Library. Example contact form and validate it backed with the help of a session in PHP.

In this tutorial explained about PHP Custom created captcha and i will teach you how to create PHP captcha code scrip using GD-Library also in this tutorial will look how to validate custom captcha code validate server-side PHP. And Last I will take an example of a contact form using this custom captcha PHP.

The Captcha code is the best solution to prevent unwanted access and spam bots or robotics handle fill-up the form. This will preview all the rights and protect your form from spammers.

If this form is filled by a bot but not able to understand the captcha code if there are humans can easy to enter the path code and submit it very well without any problem. SO this way we can prevent unwanted spam messages from the public client-side application.

There are many too available in the market that secure your input filed from the client side on the public website through the organic. like, google tool all that.

The captcha is randomly self-generated code the run time event will generate I random number specific defined code and append it to the image and this image will show on the form. When the user will fill up the form they must need to enter the given rand number digital code if it is wrong or not entered in the form it will throw an error from the server side this captcha validation example is also here given.

We will take an example of a contact form with a captcha code example and submit and validate it server side using PHP with different certain conditions.


The custom captcha code generates and applies in PHP is very easy and simple to understand for the developer. By having an end of this tutorial you will easy to implement in your website.

So let's start custom Captcha integrate with PHP with the take help of "GD Library".

Step 1: Create Captcha Image

This is the code example of how to generate captcha code in PHP, After defining the session starts, Firstly I will generate random six digits random number for the captcha using the rand() PHP function. Then we will add this generated captcha code session for the validate after submitting the form to the server. Crete simple captcha image using GD library build-in function. All Done this code will create a temporary captcha image.


    $code = rand(111111,999999);

    $_SESSION['CAPTCHA_CODE'] = $code;

    // captcha IMAGE CREATE 
    $layer = imagecreatetruecolor(168, 37);
    $captcha_bg = imagecolorallocate($layer, 000, 000, 000);
    imagefill($layer, 0, 0, $captcha_bg);
    $captcha_text_color = imagecolorallocate($layer, 255, 255, 255);
    imagestring($layer, 5, 55, 10, $code, $captcha_text_color);
    header("Content-type: image/jpeg");

Step 2: Input Form

Taken the help of Bootstrap 5 form example so we can easy to understand.

Create a simple HTML form to submit user-side details, Take some fields to the side of the form and import the captcha image from the captcha.php file by giving the patch of the file in the image tag src attribute. The form used the post method for the send HTTP request.

After submission, if any validation is passed then it will return to index.php and echo the validation error. if everything is well and the captcha is successfully validated go for further process.

<?php session_start(); ?>
<!doctype html>
<html lang="en">
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <title>Custom captcha Code PHP - Webappfix</title>
    <div class="container  mt-5">
        <div class="row">
            <div class="col-6 m-auto bg-light p-3">
                if (isset($_SESSION['captcha']) && !empty($_SESSION['captcha'])) {
                    foreach ($_SESSION['captcha'] as $key => $value) {

                        echo '<div class="alert alert-danger">'.$value.'</div>';
                <form action="submit.php" method="post">
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="inputEmail4">Email</label>
                            <input type="email" name="email" class="form-control" id="inputEmail4" placeholder="Email">
                        <div class="form-group col-md-6">
                            <label for="inputPassword4">Password</label>
                            <input type="password" name="password" class="form-control" id="inputPassword4" placeholder="Password">
                    <div class="form-group">
                        <label for="inputAddress">Address</label>
                        <input type="text" name="address_1" class="form-control" id="inputAddress" placeholder="1234 Main St">
                    <div class="form-group">
                        <label for="inputAddress2">Address 2</label>
                        <input type="text" name="address_2" class="form-control" id="inputAddress2" placeholder="Apartment, studio, or floor">
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="captcha">Enter captcha</label>
                            <input type="text" name="captcha_code" class="form-control" id="captcha">
                        <div class="form-group col-md-4">
                            <label>captcha Code</label>
                            <img src="./captcha.php" alt="">
                    <button type="submit" class="btn btn-primary">Sign in</button>
    <script src="" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>

Step 3: Submit Form & Validation Captcha

Form request handled form the contact form once request send will come here submit.php. firstly we will check the valid post form request from the client side. If it is true then it will validate the captcha.

How To Add Google reCAPTCHA v2 In HTML Form Based PHP/Laravel Website

The first condition will check whether the captcha code is empty or not if empty that means the captcha code is not filled by the user. Will send valid message to form and will see the captcha code request error.

If the captcha does not match. still, it will return with the message invalid captcha code. So last if the $error variable is not empty then it will store to session and redirect the header back to the contact form with the validation.

Finally, The form will submit and you can hand it over after the captcha code matches all been processed.


if(isset($_POST)) {

    $email = $_POST["email"];
    $password = $_POST["password"];
    $address1 = $_POST["address_1"];
    $address2 = $_POST["address_2"];
    $captchaCode = $_POST["captcha_code"];

    $filterCaptchCode = filter_var($_POST["captcha_code"], FILTER_SANITIZE_STRING);

    $error = array();

    if(empty($filterCaptchCode)) {

        array_push($error,'Please enter the captcha.');
    else if($_SESSION['CAPTCHA_CODE'] != $filterCaptchCode){
        array_push($error,'Captcha is invalid.');
    if(! empty($error)){
        $_SESSION['captcha'] = $error;

        echo 'Hurray!, You captcha Successfully Validated';

So this is a very simple and easy captcha code custom create example you can integrate anywhere when you think that the form is not safe from hacked and bots.


So in this post, I have created an HTML contact form with custom create captcha code taking the help of the GD library image build function and validating it server side to prevent unwanted form submission and bots.

We always thanks to you for reading our blogs.


Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us


Haresh Chauhan


We Are Also Recommending You :