Page 1 of 1
Help in Captch Code.
Posted: Tue Jun 28, 2011 11:48 pm
by Sagar_999
Hello.. I want to develop a simple 6 character captcha code generator, I have tried below code by myself but it generates sometimes 4 characters sometimes 5 or 6.
So kindly help me . Example(786GH4, AS325C, 90JJF4)
<?php
for($k=1;$k<=3;$k++){
$c=rand(0,91);
if($c>65 && $c<91){
echo chr($c);
}
else{
echo $c;
}
}
?>
Re: Help in Captch Code.
Posted: Wed Jun 29, 2011 2:01 am
by Apollo
Of course it's not always 6 characters, why would you think it is?
Try:
Code: Select all
for ($k=1; $k<=6; $k++)
{
$c = rand(0,35);
echo ($c<10) ? chr(ord('0')+$c) : chr(ord('A')+$c-10);
}
Re: Help in Captch Code.
Posted: Sun Jul 03, 2011 12:04 am
by Sagar_999
I got another solution.
<?php
for($k=1;$k<=6;$k++){
$c=rand(0,91);
if($c>65 && $c<91){
echo chr($c);
}
else{
$d=rand(0,9);
echo $d;
}
}
?>
Re: Help in Captch Code.
Posted: Mon Jul 04, 2011 2:49 am
by Apollo
Sagar_999 wrote:I got another solution.
This results in numbers 0-9 appearing a lot more than letters B-Z.
67 out of 92 times you'll get a number, and besides you'll never get the 'A'.
My code enforces an even distribution amongst all 36 characters (0-9 and A-Z).
I really think you're making a mistake somewhere, do you understand why you insist on doing rand(0,91)? (or was that just trial & error?

)
Re: Help in Captch Code.
Posted: Mon Jul 04, 2011 10:34 am
by Noodleyman
Why not try something a little more.... structured.
This will give you more control. Its a function I found online, and tweeked a little, its very useful and always a good random sequence.
Just adjust the characters you want displayed, and the number of characters you want also. You can add/remove more arrays to it if you want. I use this to generate random strings up to 7000 characters in length, does the job nicely
Code: Select all
function random_stuff( )
{
$character_set_array = array( );
$character_set_array[ ] = array( 'count' => 2, 'characters' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' );
$character_set_array[ ] = array( 'count' => 2, 'characters' => '0123456789' );
$character_set_array[ ] = array( 'count' => 2, 'characters' => 'abcdefghijklmnopqrstuvwxyz' );
$temp_array = array( );
foreach ( $character_set_array as $character_set )
{
for ( $i = 0; $i < $character_set[ 'count' ]; $i++ )
{
$temp_array[ ] = $character_set[ 'characters' ][ rand( 0, strlen( $character_set[ 'characters' ] ) - 1 ) ];
}
}
shuffle( $temp_array );
return implode( '', $temp_array );
}