#native_company# #native_desc#

Visual Verification in PHP

By Brett Patterson
on March 2, 2006


Many topics on the discussion forums deal with the verification of form data. Often it is checked to determine whether or not the submission is from a user or from a “bot”, if the email address entered is a valid address, or if all the information that is required has been entered into the form. While it’s fairly easy to check to see if a form field is empty, determining if the posted information came from a real human is another task altogether. Most forms now include image verification for just this reason. This article will demonstrate how to create a simplified image verification system.

Random strings, or random characters?

There are two different ways that we can go about doing this. We can use a set of pre-made sentences and randomly choose characters from those sentences, or we can randomly generate an alpha-numeric string. Both methods are going to be explained and explored in our code. Let’s get to it!

Defining some things

With our verification, we will use “random” colors for text and backgrounds. Also, we need to define a maximum length of characters that the “random” string will be. We also need to define what font we’re using and where to find it (see the next section for more information on that subject).

To make our code more portable, we’ll be using a function to create the image, so we can start by declaring the function and then our variables:

function gen_rand_img()
	 *	We define some static items here

	 ## Define our random sentences
	$sentences = array(
			'This is a random string',
			'Lorum Ipsum Doler sit amet',
			'The quick brown fox jumps over the lazy dog',
			'Kick the tires and light the fires Big Daddy'

	## Define font file
	putenv('GDFONTPATH='.realpath('.')); // Set GD font path to this directory
	$font = 'ProggyCleanSZBP'; // Leave extension off

	## Define some random colors
	## http://december.com/html/spec/colordec.html
	$bg_colors = array( ## BACKGROUND COLORS
			'176.196.222', // Blue
			'204.153.204', // Purple
			'204.204.204', // Gray
			'227.81.82', // Red
			'150.200.162'	 // Green
	$font_colors = array( ## FONT COLORS
			'0.0.139', // Blue
			'104.34.139', // Purple
			'79.79.79', // Gray
			'128.0.0', // Red
			'59.94.15'	 // Green

	$img_width = 150; ## Image Width
	$img_height = 75; ## Image height
	$fnt_size = 24;  ## Font-Size
	$let_space = 10; ## Letter Spacing
	$str_length = 6; ## Length of Random String

Colors Galore!!

We will now define some colors for the font and background of our image. We use a decimal separated value of RGB values. You can define your own colors, but they have to be RGB values. A large list of colors can be found here. Be careful when defining colors so that you don’t use colors that are too similar. You want to avoid having text that is unreadable or too difficult to read, so pick your colors wisely.

What Font??

We will now define what font we’re using. I chose to use ProggyCleanSZBP as the font for reference because it puts slashes through zeros. It helps to differentiate between 0 (zero) and O (capitol “Oh”). You can download this font (for free) from its home page at Proggy_Fonts.com. You can choose one from there, or just use your own. Just make sure it’s a TTF (True Type Font) and it’s placed in the same directory as this script.

We define the font path to be used with GD by getting the realpath to our current directory. Then, we define our font-name (which is the name of the font file). We will use it later, but these steps are required. Now how about those “random” strings?

Generating a Random String

We need to define random strings to use in the image. Once we get this part ready, it’s on to generating the image. We will write one function to create our random string, and we’ll use a series of functions to both randomize the string and randomly select a portion of that string. The code is fairly simple and straight-forward:
	function gen_random_string($length=5, $str='')
		for($i=1; $i<=$length; $i++)
			$ord = rand(48, 90);

			if( ( ($ord>=48) && ($ord<=57) ) || ( ($ord>=65) && ($ord<=90) ) )
				$str .= chr($ord);
				$str .= gen_random_string(1);
		return $str;

	## Random String or Random Sentence?
	$str_snt = rand(0,1); // 0: sentences, 1: random string

	if($str_snt == 0)
		$rnd_str = str_replace(' ', '', strtoupper($sentences[rand(0,count($sentences)-1)]));
		$rnd_str = substr($rnd_str, rand(0,strlen($rnd_str)-$str_length), $str_length);
		$rnd_str = gen_random_string($str_length);

What’s going on?

With the above code, first we’re randomizing the string to be either a sentence or alpha-numeric. Once that is “decided” for us by our script, we either generate a random string (with our function) or we select a random sub-string of a random sentence to show. Now we’ll delve into what our function does.

We start off by defining the length we want (with a default of 5) and a default string variable. Doing this helps in two ways:

  • We can also make this recursive, as we’ll explain later.
  • It has expandability

When we call the function it loops for as many times as we choose. For each loop, it generates a random number between 48 and 90. Then, it checks to make sure that the value it generated is a valid ordinal for an alpha-numeric character. Those ordinal values are 48 – 57 (numeric) and 65 – 90 (alphabetic).
If the random number is not between those values, it runs itself again (recursively) so that we get a proper valid string.

The sentence version is a bit more complicated. This one does the following (in this order):

  1. Generates a random key for use with the $sentences array
  2. Gets the sentence that is bound to the random key that we generated above
  3. Converts the string to all UPPERCASE letters
  4. Replaces all spaces with no-space so we get a long string of characters
  5. Stores the above string into a variable called $rand_str

The next line that gives us the final random string is a little tricky. So let’s break it down, one by one:

$rnd_str = substr($rnd_str, rand(0,strlen($rnd_str)-$str_length), $str_length);
Working from the inside out, the first step generates the length of our random string. Then the rand() function generates a random number from 0 (first character) to $str_length characters from the end. Our first sentence would give:
THISISARANDOMSTRING [String Length: 19] – [$str_length: 6] = 13

So we generate a random number from 0 to 13, but we do it in a dynamic way so that we can use any sentence we want. Then it’s just a matter of cutting the string $rnd_str from its random starting point (evaluated above) and spanning the next $str_length characters.

So How About That Image?

Now that we have our random string in the variable $rnd_str we can finally write the code to create the image.