random


PHP random password generator

Here is a function for random password generation, could be useful in a lot of PHP projects.


/**
* @author Petros Kyladitis - 2012
* @license MIT License
*
* @description random password generator
* @param $min_length the minimum size of the password
* @param $length the maximum size of the password
* @param $chars a string contains all acceptable password characters
* @return a string with the generated password
*/

function rand_pass($min_length, $max_length=null, $chars="qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM"){
  //if $max_length param is not set, pass $length is the $min_length 
  //param, else a random number between min and max params.
  $length = !isset($max_length) ? $min_length : rand($min_length, $max_length) ;
  
  //the position of the last character of $chars variable
  $chars_end = strlen($chars) - 1;
  
  //variable for store password
  $pass ;
  
  //select a random char from the $chars & concatenate to the $pass
  for($i=0; $i<$length; $i++)
    $pass .= substr($chars, rand(0, $chars_end), 1) ;
  
  return $pass ;
}