KB_CAPTCHA - CAPTCHA Image Generation in PHP
July 21st, 2007Introduction
KB_Captcha is a simple PHP script to generate reasonably safe CAPTCHA image to secure any public facing web application.
KB_Captcha offers the user a whole selection of options;
- Choice of base image.
- Choice of font (TTF).
- Optional sound generation for accessibility. (Linux only)
Update: 23/07/07
- I recently tried flite. Which is some promising text to speech software for Linux/Windows but it doesn’t generate very audiable results.
Table of contents
- Introduction
- What is a CAPTCHA?
- Table of Contents
- Requirements
- Usage
- Code
- Download
- Examples
- Future/Todo
- References

What is a CAPTCHA?
A CAPTCHA is a program that can tell whether its user is a human or a computer. You’ve probably seen them — colorful images with distorted text at the bottom of Web registration forms. CAPTCHAs are used by many websites to prevent abuse from “bots,” or automated programs usually written to generate spam. No computer program can read distorted text as well as humans can, so bots cannot navigate sites protected by CAPTCHAs.
Requirements
The code has been tested on Linux. It should work on Windows providing you have the right extensions enabled. Sound creation will not work on Windows at all for now.
You will need certain requirements in place to use this script;
- A PHP enviroment configured with the following’–with-gd’ ‘–with-freetype-dir’ ‘–with-png’ ‘–with-jpeg-dir’
- Only tested with PHP 5.
- Text_Password from PEAR.
- qwavjoin program from quelcom
- Ideally, access to your server’s cron.
If you don’t have access to your server, you can
- Download and Text_Password and just upload the Text_Password.php file.
- Manually delete your image& sound cache either manually or from a remotely managed cron.
Usage
The code is split into two parts. The create_kb_captcha function itself and the page that calls the function, usually a web form.
The code also requires certain outside files, don’t worry they are included in the download;
- A base image (PNG format)
- A True Type font
- A-Z & 0-9 WAV files
You will need reasonable HTML knowledge to implement this system.
The main function is as follows
create_kb_captcha($base_image=”",$font=”",$lines=0,$create_sound=”1″)
Where;
- $base_image is the base image PNG file that will have form the background of the CAPTCHA.
- $font is the True Type font that will be used for the text
- $lines is the amount of lines to obfuscate the text somewhat.
- $create_sound tells the script to create a wav file for accessibilty purposes. Set this to 0 if on Windows.
You will also need to create a cache directory that is writable by your web server.
Code
kb_captcha_example.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | function kb_create_captcha($base_image="",$font="",$lines=0,$create_sound="1"){ $in = Text_Password::create(8, 'unpronounceable', 'alphanumeric'); $_SESSION['captcha_image'] = $in;// check ttf exists if (!is_file($font)) { echo 'Missing true type font.'; exit(); } // check base image exists if (!is_file($base_image)) { echo 'Missing base_image'; exit(); } // load the base image $captcha_base_image = imagecreatefrompng($base_image); // define the text colours $shadow_colour = imagecolorallocate($captcha_base_image, 255, 255, 255); $text_color = imagecolorallocate($captcha_base_image, 0, 0, 0); // Add a shadow to the text imagettftext($captcha_base_image, 24, 2, 30, 42, $shadow_colour, $font, $in); // Add the text imagettftext($captcha_base_image, 24, 2, 28, 40, $text_color, $font, $in); // make lines if ($lines != 0) { $image_info = getimagesize($base_image); $i = 1; while ($i <= $lines) { $random_line_colour = ImageColorAllocate($captcha_base_image, rand(0,255), rand(0,255), rand(0,255)); imageline($captcha_base_image,rand(20,$image_info[0]), rand(10,$image_info[1]), rand(20,$image_info[0]), rand(10,$image_info[1]),$random_line_colour); $i++; } } // create the image imagepng($captcha_base_image,'cache/'.md5($in).'.png'); // make some noise if ($create_sound == '1') { $arr_letters = str_split($in); $str_letters = ""; foreach($arr_letters as $foo){ $str_letters .= "sounds/".strtolower($foo).".wav "; } // create the file exec('/usr/bin/qwavjoin -o cache/'.md5($in).'.wav '. $str_letters,$ret); } if (!is_file('cache/'.md5($in).'.png')) { echo 'Error making image.'; } if ($create_sound == '1') { if (!is_file('cache/'.md5($in).'.wav')) { echo 'Error making sound.'; } } } |
kb_captcha_example.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | session_start(); require_once "Text/Password.php"; require_once "kb_captcha_image.php";if ($_SERVER['REQUEST_METHOD'] == 'GET') { kb_create_captcha($base_image="badge3.png",$font="28 Days Later.ttf",$lines="10",$create_sound="1"); echo '<h1>KB Captcha Example</h1>'; echo '<form method="POST" name="form1">'; echo '<img src="cache/'.md5($_SESSION['captcha_image']).'.png" /> <a target="_new" href="cache/'.md5($_SESSION['captcha_image']).'.wav"><img src="sound.png" border="0" alt="Listen"></a><br />'; echo '<input type="text" name="captcha_image" /> '; echo '<input type="submit" name="submit" value="submit" />'; echo '</form>'; } elseif ($_SERVER['REQUEST_METHOD'] == 'POST') { echo 'I said: ' .strtolower($_SESSION['captcha_image']) .'<br />' . 'You said: ' .strtolower($_POST['captcha_image']) .'<br /><br />'; if (strtolower($_SESSION['captcha_image']) != strtolower($_POST['captcha_image'])) { echo "CAPTCHA doesn't match."; } else { echo 'Good match'; } } |
Download
- Copy the two code snippets above and save to your server.
- Download extras file - it includes base images, font, sounds and icons.
- Download qwavjoin for Linux (From Ubuntu).
Examples
Future
Known issues so far
- There is no cache clean up routines.
- Firefox doesn’t appear to play the whole WAV file. It works fine in Internet Explorer.
Who knows what the future holds. Some of the features I plan shortly are;
- Animated obfuscating lines.
- Extra code security.
- Alternative sounds. Do you know of any?
- Needs to be more Windows friendly.
- Accessibility accreditions.
References
- sound.png is from Fam Fam Fam
Silk Icon Set. - 28 Days Later from was downloaded from DaFont originally by Jens R. Ziehn .
- Sounds are from BeVocal. If these are not freely redistributable - please let me know.
I’ve put a lot of hours into this script. Please give generously!
| Bookmark it del.icio.us | Reddit | Slashdot | Digg | Facebook | Technorati | Google | StumbleUpon | Window Live | Tailrank | Furl | Propeller | Yahoo |
Was this post useful to you? Let me know, buy me a beer!
Alternatively, if you're feeling impecunious, you may like to subscribe to my RSS feed, or see other articles in the HTML, CSS, AJAX, PHP category.