Thursday, September 13, 2012

PHP: Produce random string for password

Below is the PHP function to produce random string for passwords:
Method 1:  Random pickup letters and number

//$length is the string length to produce
    function generate_rand($length){
  $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  //microtime() return microsecond part of unix time, betwee 0-1
  for($i=0; $i<$length; $i++) {
      $rand.= $c[rand()%strlen($c)];
  return $rand;
 //Produce password with 6 letters+number
  echo generate_rand(6);


Method2: Produce a password more like a word, easy to remember, such as ninotu
function readable_random_string($length){
   $conso=array("b","c","d","f","g","h","j","k","l", "m","n","p","r","s","t","v","w","x","y","z");   
   $max = $length/2;

//For random number rand() initialization
    for($i=1; $i<=$max; $i++)    {
    return $password;

  echo readable_random_string(6);

No comments:

Post a Comment