1

Possible Duplicate:
PHP: How to generate a random, unique, alphanumeric string?

i want to generate random token [alphanumeric] for random length [between 4-6] characters.
Can anyone help ?

Community
  • 1
  • 1
Sourav
  • 17,065
  • 35
  • 101
  • 159

3 Answers3

9

You could use uniqid (search for "token" in the examples given there) and shorten it with substr.

halfer
  • 19,824
  • 17
  • 99
  • 186
Mike
  • 367
  • 4
  • 8
4

Firstly, you can just get a random number between 10+26+26=62 6 times, and then calculate the resulted string, this seems easy enough.

<?php
function ()
{
$letters={a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,0,1,2,3,4,5,6,7,8,9,10}
return array_rand($letters).array_rand($letters)......... // you get the point

?> 
fingerman
  • 2,440
  • 4
  • 19
  • 24
2

or if you prefer the 'hard' way...

$len = random(4,6);
$token = array();
for ($i = 0; $i < $len; $i++) {
  $ord = 0;
  switch(random(1,3)) {
    case 1: // 0 - 9
      $ord = random(48,57);
      break;
    case 2: // A - Z
      $ord = random(65,90);
      break;
    case 3: // a - z
      $ord = random(97,112);
      break;
  }
  $token[] = chr($ord);
}
LeleDumbo
  • 9,192
  • 4
  • 24
  • 38
  • this wouldn't be really random, much higher chances of getting an '3' then on 'O'... see my method for a better solution – fingerman Jun 14 '11 at 15:21
  • I was about to give that as well, but I'm too lazy to write all those alphanumeric chars. anyway, how can you say that the chance of getting '3' is higher? – LeleDumbo Jun 14 '11 at 15:48
  • cause, to get '3' you have 1-3 choice, and then 1-10, total 1/30 to get 'O' you have 1-3 choice, and then 1-26, total 1/78. therefore, this method isn't good enough... – fingerman Jun 14 '11 at 22:43
  • I see, the randomness isn't uniformly distributed... – LeleDumbo Jun 15 '11 at 06:54