Home    posts    php captcha

Posted on: October 27, 2017

Create Captcha from scratch using PHP GD library

So today, we are going to make a simple Captcha PNG image generator using built-in PHP GD library functions. For the purpose of this tutorial, things will be kept at minimum base level, yet customizable for a variety of needs. The plan itself is to create an image with your favourite image manipulation toolkit that will be used as background and to download the font of your choice to be used for the code generated. I will be using GIMP and Tahoma font for this demonstration.

PART 1 - Create the background image and download the font

To create a background image for captcha, I will use 100x40 pixels and airbrush tool with chalk 02 option. Color will be black, see the image below. After, we will export it as PNG image to the images folder. To complete this part, you have to download the font of your choice and place it in the fonts folder.

PART 2 - Create Captcha image

Now that everything is ready, we will proceed to coding. First we will create a random string of certain length from defined characters pool. This will then be added to the newly created captcha image.


<?php 

// Characters pool of all lowercase and uppercase chars of English alphabet and all digits
$charpool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

// The length of the code generated and an empty string in which we will append generated code from the loop
$codelen = 6;
$code = '';

// For all the x'es between 0 and the length of $codelen variable, generate the code from the charpool, using PHP rand function
for($x = 0; $x < $codelen; $x++) {$code .= $charpool[rand(0, strlen($charpool) - 1)];}

// Tell PHP that the content type will be a PNG image
header("Content-type: image/png");

// Create an image from our above created image and save it into a variable. Note that you have to provide the path to it
$image = imagecreatefrompng('images/cap.png'); 

// Allocate white color to text, the code is RGB
$textcolor = imagecolorallocate($image, 255, 255, 255);

// Provide path to the font. I had to use dot slash ./ before the path in order to make it work
$font = './fonts/tahoma.ttf';

// Generate image from all the settings, $image, $textcolor, $font, $code.
// The numbers from left to right are font size, inclination, horizontal position and vertical position
imagettftext($image, 15, 3, 16, 29, $textcolor, $font, $code); 

// Display image as PNG and then destroy it after it's used
imagepng($image);
imagedestroy($image);

All you need now is to save the code as a .php file and run it through browser. It will generate an image with different code each time the page is refreshed, giving the desired Captcha effect.


Comments:

Be the first to comment.

Add a comment:










I have read and agree with the Privacy terms and conditions.