oliverbj
oliverbj

Reputation: 6050

PHP - Captcha generating wrong character length

I have this captcha script that should generate a length of 4 characters. It does that - most of the times. Although, sometimes, it will generate 3 letters instead of 4. I simply can't find the error.

This is the script to generate length:

  $_chars = "0123456789ZXCVBNMASDFGHJKLQWERTYUIOP";

    for($l = 0; $l<4; $l++){


        $temp = str_shuffle($_chars);


        $char = mt_rand(0, strlen($temp));


        $_charcode .= $temp[$char];


    }

Upvotes: 0

Views: 125

Answers (1)

Hanky Panky
Hanky Panky

Reputation: 46910

The max parameter (second ) to your random function should be 1 less than the length of your string because indexes start at 0, and you are using that index for an array later in your code.

$char = mt_rand(0, strlen($temp));  // Goes out of bounds on some runs

should be

$char = mt_rand(0, strlen($temp)-1);   // This way you wont get a blank one

Here is a fiddle with 500 runs.

Fiddle

Upvotes: 3

Related Questions