Jump to content

Generating random alphanumeric string


mallen

Recommended Posts

I am working on creating a cusom captcha. It creates a random alphanumeric string. I set the value for the total characters to "5" but sometimes it will only display 4 characters. Is this a result of the rand function?

session_start();
error_reporting(E_ALL ^ E_NOTICE);

$image = @imagecreatetruecolor(120, 30) or die("Cannot Initialize new GD image stream");
// set background and allocate drawing colours
$background = imagecolorallocate($image, 0x66, 0x99, 0x66);
imagefill($image, 0, 0, $background);
$linecolor = imagecolorallocate($image, 0x99, 0xCC, 0x99);
$textcolor1 = imagecolorallocate($image, 0x00, 0x00, 0x00);
$textcolor2 = imagecolorallocate($image, 0xFF, 0xFF, 0xFF);
$lines = 5;
// draw random lines on canvas
for($i=0; $i < $lines; $i++) { imagesetthickness($image, rand(1,3));
imageline($image, 0, rand(0,30), 120, rand(0,30) , $linecolor); }


$string = '';
$total_characters = 5;
$random_dots = 5;
$font_size = 16;
$possible_letters = '2345678abcdefghjkmnpqrtwyABCDEFGHJKMNPQRTWY';

 
$fonts = array(); 
$fonts[] = "fonts/font1.ttf";
$fonts[] = "fonts/font2.ttf";
$fonts[] = "fonts/font3.ttf";


for( $i=0; $i<$random_dots; $i++ ) 
{
    imagefilledellipse($image, mt_rand(0,120),
    mt_rand(0,30), 2, 3, $image_noise_color);
}

session_start();
$i = 0;
$digit = '';
for($x = 15; $x <= 95; $x += 20 ) {

while ($i < $total_characters ) { $i++; $x += 15;
$textcolor = (rand() % 2) ? $textcolor1 : $textcolor2;
$digit .= ($num = $possible_letters[rand(0,strlen($possible_letters))]);

imagettftext($image, $font_size, 0, $x, 20, $textcolor, $fonts[array_rand($fonts)], $num);}}

$_SESSION['digit'] = $digit;  
header('Content-type: image/png'); imagepng($image); imagedestroy($image); 
Link to comment
https://forums.phpfreaks.com/topic/285012-generating-random-alphanumeric-string/
Share on other sites

The problem is in the parameters being used in rand():

$digit .= ($num = $possible_letters[rand(0, strlen($possible_letters))]);

$num is being defined as a letter from $possible_letters with an index defined by rand() between 0 and the length of $possible_letters.

 

Think about 1) the index that represents the first letter (0) and 2) what you are defining as the last possible index.

 

It might be easier to visualize with a smaller string. So, let's say you have a string of "ABCDE". That string has a length of 5. If "A" is at position 0, then "B" is at position 1, "C" at position 2, "D" at position 3, and "E" at position 4. So, setting the max index at the length of the string will make it possible to set an index that is 1 greater than the last character (i.e. 5 instead of 4).

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.