Friday, 13 April 2012

Random String Generator in PHP

There are many occasions where you might require a random string in your application. It may be used for generating a key for an encryption algorithm or just to supply a random password to a user. Here a simple PHP function gen_rand_str() is given which can meet these requirements.


The function returns the random string of required length. The length of the string returned can be either pre-programmed or can be a random value. A change in a single line of code will do the trick.
Here is the PHP code listing:

<?php
function gen_rand_str()
{
  $source = "abcdefghijklmnopqrstuvwxyz";
  $source.= "0123456789";
  $source.= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  $len = 10;
//  $len = rand(8,12);
  $str = "";
  for($i=0;$i<$len;$i++)
  {
    $str.=$source[rand(0,strlen($source)-1)];
  }
  return $str;
}
?>


The code is straight forward and self explanatory. The $source variable contains the list of all the symbols that might appear in the generated string. You can add more or delete from them according to the requirement. The $len variable determines the length of the output. It can take any value above 0. Here it is given as 10. The next line of code is commented. If you want a string of random length then uncomment that statement. The two values given in the rand function gives the possible values $len can have. Here rand(8,12) means that the string can take any value from 8 to 12. The final result is stored in $str which is returned.

No comments:

Post a Comment