Image Verification with PHP
I started experimenting with the GD image functions and decided there was no better way to test them out then to create a simple image verification script. So read on and I’ll show you what I got.
The script is pretty simple, it creates a random string in the form of word1_word2#. For example: mess_week94. It uses PHP’s native session functionality (I know, eeew! :-P). The form itself is simple, could be edited for more fields (obviously). See the screenshot for an example.
So read on if you want ![]()
The first thing is the custom makeVerifyString() function:
[code lang="php"]
function makeVerifyString()
{
$words = array( 'cat', 'dog', 'animal', 'zoo', 'snoopy', 'keyboard', 'computer', 'mouse', 'joystick', 'at', 'tab', 'drink',
'food', 'water', 'fall', 'pet', 'book', 'learn', 'school', 'teacher', 'screen', 'government', 'police',
'trouble', 'double', 'triple', 'visual', 'language', 'cool', 'hot', 'cold', 'boil', 'route', 'task',
'boss', 'create', 'edit', 'move', 'delete', 'start', 'end', 'max', 'min', 'star', 'point', 'take', 'steal',
'borrow', 'cap', 'gun', 'fire', 'work', 'pay', 'loan', 'buy', 'soda', 'speaker', 'board', 'help', 'ask',
'floor', 'root', 'top', 'bottom', 'queen', 'king', 'mess', 'total', 'some', 'little', 'lot', 'bunch',
'day', 'night', 'week', 'year', 'decade', 'month', 'tide', 'wave', 'travel', 'pause', 'break', 'continue',
'print', 'lock', 'insert', 'movie', 'show', 'cartoon', 'animate', 'mortal', 'canon', 'percent', 'dash',
'add', 'subtract', 'divide', 'multiply', 'quote', 'comma', 'slash', 'arrow', 'lead', 'follow', 'question',
'stupid', 'smart', 'answer', 'money', 'character', 'letter', 'paragraph', 'enter', 'exit', 'word', 'desk',
);
$num = count($words) - 1;
$string = $words[ mt_rand(0, $num) ];
$string .= '_';
$string .= $words[ mt_rand(0, $num) ];
$string .= mt_rand(0, 99);
return $string;
}
?>[/code]
Here I just defined an array of words to use. You can easily edit this to use some huge wordlist or something, but for simplicity I kept it all in one function. Then it just creates the string by selecting two random words and a number.
Next let’s take a look at our createImage() function:
[code lang="php"]
function createImage($string, $filename = 'verify.jpg')
{
$img['string'] = $string;
$img['font'] = 5;
$img['font_width'] = ImageFontWidth($img['font']);
$img['font_height'] = ImageFontHeight($img['font']);
$img['padding'] = 10;
$img['img_width'] = (strlen($img['string']) * $img['font_width']) + ($img['padding'] * 2);
$img['img_height'] = $img['font_height'] + ($img['padding'] * 2);
$img['img'] = ImageCreate($img['img_width'], $img['img_height']);
////////////////////
$colors = array('white' => ImageColorAllocate( $img['img'], 255 , 255 , 255 ),
‘black’ => ImageColorAllocate( $img['img'], 0 , 0 , 0 ),
‘red’ => ImageColorAllocate( $img['img'], 255 , 0 , 0 ),
‘green’ => ImageColorAllocate( $img['img'], 0 , 255 , 0 ),
‘blue’ => ImageColorAllocate( $img['img'], 0 , 0 , 255 ),
‘orange’ => ImageColorAllocate( $img['img'], 255 , 128 , 0 ),
‘pink’ => ImageColorAllocate( $img['img'], 255 , 0 , 255 ),
‘purple’ => ImageColorAllocate( $img['img'], 128 , 0 , 255 ),
‘yellow’ => ImageColorAllocate( $img['img'], 255 , 255 , 0 ),
‘navy’ => ImageColorAllocate( $img['img'], 0 , 0 , 128 ),
‘maroon’ => ImageColorAllocate( $img['img'], 128 , 0 , 0 ),
‘gold’ => ImageColorAllocate( $img['img'], 128 , 128 , 0 ),
’silver’ => ImageColorAllocate( $img['img'], 192 , 192 , 192 ),
‘gray’ => ImageColorAllocate( $img['img'], 128 , 128 , 128 ),
);
////////////////////
// Fill for background
ImageFill($img['img'], 0, 0, $colors['white']);
// Create some background lines ![]()
for($x = 0; $x < $img['img_width']; $x += 20)
{
ImageLine($img['img'], $x, $img['img_height'], $x + 15, 0, $colors['silver']);
}
// Print the stirng onto it
ImageString($img['img'], $img['font'], $img['padding'], $img['padding'], $img['string'], $colors['blue']);
// Output it into a file
ImageJpeg($img['img'], $filename);
}
?>[/code]
You pass this function the string to use (and the optional filename to write to). GD comes bundled with default fonts numbered 1-5. Here’s a table of font and sizes:
| Font Number | Width | Height |
| 1 | 5 | 6 |
| 2 | 6 | 8 |
| 3 | 7 | 13 |
| 4 | 8 | 15 |
| 5 | 9 | 15 |
If you want to use your own fonts, you can read up on the different font functions here.
The padding is just how many pixels should be around the text. We use the padding combined with the font width and height to figure out the dimensions of the image.
Now to use colors, you have to allocate it to the image we’re working with (which is in $img['img']$colors array with a bunch of common colors.
The next thing we do is create a solid background using ImageFill(). I’ve got the background set to white, you can change it by substituting another one of the $colors in.
The next block is a for loop. I just wanted to add some “style” to the image, so this loop is responsible for drawing those diagonal lines across the background of the image.
ImageString(), as you might have guessed, writes the text to the image. We use the padding to position the text in the middle of the canvus. Again, you can change the color by substituting a different $colors in with the blue that’s there now.
Then finally, we write the image to the file with ImageJpeg().
Now here’s the full script including the session work etc:
[code lang="php"]
session_start();
if(isset($_POST['submit']))
{
if(trim($_POST['verify']) != $_SESSION['verify'])
die('Sorry, please go back and try the image verification again.');
else
{
session_destroy();
die('Thanks, you win.');
}
}
else
{
// incase they pressed the back button.
// make sure to only create a new
// imgae when needed
if(!isset($_SESSION['verify']))
{
$verify = makeVerifyString();
$_SESSION['verify'] = $verify;
createImage($verify);
}
?>
Verify:
}
//===============================================================================
// makeVerifyString
// - Randomly create a verify string in the form of:
//
//===============================================================================
function makeVerifyString()
{
$words = array( ‘cat’, ‘dog’, ‘animal’, ‘zoo’, ’snoopy’, ‘keyboard’, ‘computer’, ‘mouse’, ‘joystick’, ‘at’, ‘tab’, ‘drink’,
‘food’, ‘water’, ‘fall’, ‘pet’, ‘book’, ‘learn’, ’school’, ‘teacher’, ’screen’, ‘government’, ‘police’,
‘trouble’, ‘double’, ‘triple’, ‘visual’, ‘language’, ‘cool’, ‘hot’, ‘cold’, ‘boil’, ‘route’, ‘task’,
‘boss’, ‘create’, ‘edit’, ‘move’, ‘delete’, ’start’, ‘end’, ‘max’, ‘min’, ’star’, ‘point’, ‘take’, ’steal’,
‘borrow’, ‘cap’, ‘gun’, ‘fire’, ‘work’, ‘pay’, ‘loan’, ‘buy’, ’soda’, ’speaker’, ‘board’, ‘help’, ‘ask’,
‘floor’, ‘root’, ‘top’, ‘bottom’, ‘queen’, ‘king’, ‘mess’, ‘total’, ’some’, ‘little’, ‘lot’, ‘bunch’,
‘day’, ‘night’, ‘week’, ‘year’, ‘decade’, ‘month’, ‘tide’, ‘wave’, ‘travel’, ‘pause’, ‘break’, ‘continue’,
‘print’, ‘lock’, ‘insert’, ‘movie’, ’show’, ‘cartoon’, ‘animate’, ‘mortal’, ‘canon’, ‘percent’, ‘dash’,
‘add’, ’subtract’, ‘divide’, ‘multiply’, ‘quote’, ‘comma’, ’slash’, ‘arrow’, ‘lead’, ‘follow’, ‘question’,
’stupid’, ’smart’, ‘answer’, ‘money’, ‘character’, ‘letter’, ‘paragraph’, ‘enter’, ‘exit’, ‘word’, ‘desk’,
);
$num = count($words) - 1;
$string = $words[ mt_rand(0, $num) ];
$string .= ‘_’;
$string .= $words[ mt_rand(0, $num) ];
$string .= mt_rand(0, 99);
return $string;
}
//===============================================================================
// createImage
// - Creates the image file so we can use it
//===============================================================================
function createImage($string, $filename = ‘verify.jpg’)
{
$img['string'] = $string;
$img['font'] = 5;
$img['font_width'] = ImageFontWidth($img['font']);
$img['font_height'] = ImageFontHeight($img['font']);
$img['padding'] = 10;
$img['img_width'] = (strlen($img['string']) * $img['font_width']) + ($img['padding'] * 2);
$img['img_height'] = $img['font_height'] + ($img['padding'] * 2);
$img['img'] = ImageCreate($img['img_width'], $img['img_height']);
////////////////////
$colors = array(’white’ => ImageColorAllocate( $img['img'], 255 , 255 , 255 ),
‘black’ => ImageColorAllocate( $img['img'], 0 , 0 , 0 ),
‘red’ => ImageColorAllocate( $img['img'], 255 , 0 , 0 ),
‘green’ => ImageColorAllocate( $img['img'], 0 , 255 , 0 ),
‘blue’ => ImageColorAllocate( $img['img'], 0 , 0 , 255 ),
‘orange’ => ImageColorAllocate( $img['img'], 255 , 128 , 0 ),
‘pink’ => ImageColorAllocate( $img['img'], 255 , 0 , 255 ),
‘purple’ => ImageColorAllocate( $img['img'], 128 , 0 , 255 ),
‘yellow’ => ImageColorAllocate( $img['img'], 255 , 255 , 0 ),
‘navy’ => ImageColorAllocate( $img['img'], 0 , 0 , 128 ),
‘maroon’ => ImageColorAllocate( $img['img'], 128 , 0 , 0 ),
‘gold’ => ImageColorAllocate( $img['img'], 128 , 128 , 0 ),
’silver’ => ImageColorAllocate( $img['img'], 192 , 192 , 192 ),
‘gray’ => ImageColorAllocate( $img['img'], 128 , 128 , 128 ),
);
////////////////////
// Fill for background
ImageFill($img['img'], 0, 0, $colors['white']);
// Create some background lines ![]()
for($x = 0; $x < $img['img_width']; $x += 20)
{
ImageLine($img['img'], $x, $img['img_height'], $x + 15, 0, $colors['silver']);
}
// Print the stirng onto it
ImageString($img['img'], $img['font'], $img['padding'], $img['padding'], $img['string'], $colors['blue']);
// Output it into a file
ImageJpeg($img['img'], $filename);
}[/code]
Follow the comments, it's pretty self-explanitory. We start the session with session_start(), then check to see if the form was submitted (by seeing if $_POST['submit'] is set). If the form was submitted, we compare the value of the inputted verify code with the verify code we put in the session vars.
If the form is not submitted, then we want to show the form. The first thing we do is check to see if $_SESSION['verify'] is already set. If a user got the code wrong and hit the back button, then we don’t want the script to regenerate the image (well, we do. But the browser will likely cache the image and the user would have to explicitly refresh the page to get a new image). So if it isn’t set, we create a new verify code with makeVerifyString() and set it to the users session then create the image with createImage(). From there it’s as simple as the HTML form.
June 9th, 2006 at 8:49 pm
ads
August 9th, 2006 at 8:37 am
Works!!!
November 25th, 2006 at 8:59 pm
great!