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

 <?php
//$length is the string length to produce
    function generate_rand($length){
  $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  //microtime() return microsecond part of unix time, betwee 0-1
  srand((double)microtime()*1000000);
 
  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
 <?php
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");   
   $vocal=array("a","e","i","o","u");
   $password="";
   $max = $length/2;

//For random number rand() initialization
  srand((double)microtime()*1000000); 
    for($i=1; $i<=$max; $i++)    {
      $password.=$conso[rand(0,19)];
      $password.=$vocal[rand(0,4)];
 }
    return $password;

}
  echo readable_random_string(6);
  ?>

No comments:

Post a Comment