Alphanumeric Captcha values in PHP

Alphanumeric Captcha values in PHP

In my last article, I used the following code to create a random numeric value:

// 1000-9999 gives 5832 possibilies, strong enough for most captcha uses.
$VerificationCode = rand(1000, 9999);

You can use the following code instead to create a random alphanumeric value instead:

// This function will return a 5-length alphanumeric value.
// It will produce one out of 550731776 possible values.
function createCaptchaCode() {
  $stringChoices = array(
  'a','b','c','d','e','f','g','h','i','j','k','m','n','p','q','r','s','t','u','v','w','x','y','z',
  'A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z',
  '2','3','4','5','6','7','8','9');

  $code = '';
  for( $loop_b = 1; $loop_b <= 5; $loop_b++ ) {
    $code .= $stringChoices[mt_rand(0,count($stringChoices)-1)];
  }
  return $code;
}

I suppose the above function could be written in PHP as simple as this:

function createCaptchaCode2() {
	$code = substr(str_shuffle('abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'),0,5);
	return $code;
}

You might have noticed that the following characters are missing: 1, I, l, o, O and 0. This is to prevent unnecessary user frustration (they are very similar).

This covers how to generate a random alphanumeric value, what about encryption when you’re sending it between web pages? This subject is bigger than I thought it would be, so I’m going to make a new article on it.

You’ll find it here when it’s ready.

Leave a Reply