PHP Captcha code verification tutorial

Simple PHP Captcha code verification system

In this tutorial we’ll create a simple PHP Captcha code verification system.

Basically this tutorial is about how to create your own custom captcha code verification system using php.

Before we start to creating this system, let’s have a look screenshot of our captcha code verification  system –

screenshot of php captcha code verification system

To create this application we need to create just two files –

Folder structure of our application.

  • image.php
  • index.php

step – 1

First we’ll create our captcha image. For creating our captcha image we’ll use php imagecreate function.

  • Click here to learn more about php imagecreate function.
  • Click here to learn how to create an image using PHP.


header("Content-Type: image/png");
// Generating Random Numbers Between 1 to 99
$sum1 = rand(1,99); // First Number
$sum2 = rand(1,99); // Second Number
//Save the sum of the first and second number into the session.
$_SESSION['captcha_code'] = $sum1 + $sum2;
$im = imagecreate(100, 30);// SET WIDTH AND HEIGHT
$background_color = imagecolorallocate($im, 0, 0, 0); // SET IMAGE BACKGROUND COLOR
$text_color = imagecolorallocate($im, 255, 255, 255); // SET IMAGE TEXT COLOR
imagestring($im, 5, 25, 7,  $sum1 .' + '. $sum2, $text_color);

Step – 2

After creating the captcha image, now time to create our index.php file.


<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PHP Captcha</title>
box-sizing: border-box;
-webkit-box-sizing: border-box;
font-family: sans-serif;
padding: 20px;
margin: 0;

max-width: 400px;
margin: 0 auto;
padding: 10px;
border: 1px solid #ccc;

text-align: center;
width: 100%;
padding: 10px;
outline: none;
margin: 5px 0;
color: #FFF;
padding: 10px;
font-size: 20px;
font-weight: bold;

color: #FFF;
padding: 10px;
font-size: 20px;
font-weight: bold;

<div class="container">
<h1>PHP Captcha</h1>
<form action="" method="POST">
<img class="captchaImg" src="image.php">
<input type="text" autocomplete="off" placeholder="Enter your answer" name="captcha_code" />
<input type="submit">
if(isset($_POST['captcha_code']) && isset($_SESSION['captcha_code'])){
// check user answer is equal to session captcha code
if($_POST['captcha_code'] == $_SESSION['captcha_code']){
echo '<div class="success_message">Captcha code is right.</div>';
echo '<div class="error_message">Invalid captcha code.</div>';

Now run this app on your local server and check it. If you face any problem to create this application just drop your comment.

Posts Navigation

Leave a Reply

Your email address will not be published. Required fields are marked *