While working on a project last week, i used this function to generate random passwords. There are many styles of password generator available over the net, but it depends which one suits the taste and need.

The function i used has the ability of creating random password from the given set of characters with digits. So lets have a look at the code 1st and explain it after that:

<?php
function randpassword() {
  $length = 8;
  $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
  $string = "";

  for ($p = 0; $p &lt; $length; $p++) { 
    $string .= $characters[mt_rand(0, strlen($characters)-1)]; 
  }
  return $string; 
} 

echo randpassword(); 
?>

mt_rand() is PHP function to return the desired min and max number given to it. For example mt_rand(2, 10) will generate random numbers between 2 and 10. In the above line, we pass 0(zero) and then characters length with -1, please note that -1 is necessary here to avoid index out of bounds error. If you miss -1, the function will sometime generate 7 characters with error index out of bound. That’s because we are using mt_rand function which will sometime return integer $max and there will be no proper value in $characters[strlen()].