We all have encounter captcha images many times while filling online forms, or during a registration. Captchas are a necessary evil, and this post will teach you how they’re made.
Please note that this post is going to teach you how to generate simple captcha image. There are better third party solution available such as ReCaptcha, this tutorial aims merely to explain and demonstrate how such technology actually works.
You must have the GD(Graphics Draw) library installed before proceeding. This library enables drawing of graphics and images through built-in PHP functions. To install it, run
sudo apt-get install php5-gd
The first step is setting to header to image header for proper display of our image.
Creating an Image
Then we are going to create an blank image of a specific size. In this tutorial we have created an image with width 200px and height 100px.
$image = @imagecreate(200, 100) or die("Cannot Initialize new GD image stream")
Next we have to give it a background color and text color.
$bg_color = imagecolorallocate($image, 255, 255, 255); $text_color = imagecolorallocate($image, 0, 0, 0);
Writing characters on the image
Now we need to write some chatacters on the image, for that first need to generate some random character. I am going to diaplay 5 numbers on the image.
$chars = " 0123456789"; $text = substr(str_shuffle($chars), 0, 5);
After generating random numbers, we need to write them on the image and for that i am going to use imagettftext() function.
imagettftext($image, $font_size, $angle, $xpos, $ypos, $text_color, 'XENOWORT.TTF', $text);
1. $image – GD image stream
2. $font_size : Font size of the text that is displayed on the image.
3. $angle : At which angle it should display the text.
4. $xpos : X-axis of the text.
5. $ypos : Y-axis of the text.
6. $text_color : Color of the text.
7. XENOWORT.TTF : The path to the TrueType font you wish to use
8. $text : The text that is to be displayed
This file contain code that generate the captcha images
<?php /** * PHP GD * create a simple captcha image with GD library * */ //setting the image header in order to proper display the image header("Content-Type: image/png"); //try to create an image $image = @imagecreate(200, 100) or die("Cannot Initialize new GD image stream"); //set the background color of the image $bg_color = imagecolorallocate($image, 255, 255, 255); //set the color for the text $text_color = imagecolorallocate($image, 0, 0, 0); //random number $chars = " 0123456789"; $text = substr(str_shuffle($chars), 0, 5); //add the string to the image $font_size = 30; $angle = rand(1, 10); $xpos = rand(10, 50); $ypos = rand(50, 70); imagettftext($image, $font_size, $angle, $xpos, $ypos, $text_color, 'XENOWORT.TTF', $text); //outputs the image as png imagepng($image); //frees any memory associated with the image imagedestroy($image); ?>