Page 1 of 1

random alphanumeric code generation

Posted: Mon Jun 12, 2006 10:55 am
by myheadhurts
hi all,

my first post here.

I have searched the index, but can't find how to do this


I am rewriting an old perl script that had these two lines

my @chars=('A'..'Z','a'..'z','0'..'9');
my $reference = join'',map $chars[rand @chars],1..14;

and i'd like to rewrite the same thing in php - but do I need to make an array, select elements an join them or is php cleverer than that???? Is there a standard way of doing this? Is there even a php makerandomalphanumericcode() function (that wold be nice)

thanks for any help!

Jules

Posted: Mon Jun 12, 2006 11:00 am
by tecktalkcm0391
I use this to make a code without the letters and Numbers: I,O,Q,1,0,L and I think a few other ones that look a like.

Code: Select all

$code = ''; 
        $chars = array(50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 77, 78, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90); 
		$chars = array_map('chr', $chars); 
        $pool = implode('', $chars); 
		$size = strlen($pool) - 1; 
        for($i = 0; $i < $len; ++$i) 
        { 
          $code .= $pool[mt_rand(0, $size)];
If you want to change it you just need to add the character number or change them to have the numbers that match the ASCII numbers on: http://www.lookuptables.com/

Posted: Mon Jun 12, 2006 11:03 am
by onion2k
tecktalkcm0391 wrote:I use this to make a code without the letters and Numbers: I,O,Q,1,0,L and I think a few other ones that look a like.

Code: Select all

$code = ''; 
        $chars = array(50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 77, 78, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90); 
		$chars = array_map('chr', $chars); 
        $pool = implode('', $chars); 
		$size = strlen($pool) - 1; 
        for($i = 0; $i < $len; ++$i) 
        { 
          $code .= $pool[mt_rand(0, $size)];
Why don't you just do "$pool = '23456789ABCDEFGHJKMNPRSTUVWXYZ';" instead of mucking about with array_map() and stuff?

Posted: Mon Jun 12, 2006 11:14 am
by Maugrim_The_Reaper
I'm lazy, I just make a sha1()/sha256() call across the output from uniqid() and select a substring for the proper length...

Posted: Mon Jun 12, 2006 11:18 am
by tecktalkcm0391
onion2k wrote:
tecktalkcm0391 wrote:I use this to make a code without the letters and Numbers: I,O,Q,1,0,L and I think a few other ones that look a like.

Code: Select all

$code = ''; 
        $chars = array(50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 77, 78, 80, 82, 83, 84, 85, 86, 87, 88, 89, 90); 
		$chars = array_map('chr', $chars); 
        $pool = implode('', $chars); 
		$size = strlen($pool) - 1; 
        for($i = 0; $i < $len; ++$i) 
        { 
          $code .= $pool[mt_rand(0, $size)];
Why don't you just do "$pool = '23456789ABCDEFGHJKMNPRSTUVWXYZ';" instead of mucking about with array_map() and stuff?
I dunno, thats what came out of viewtopic.php?t=49300