Generating Random Strings in PHP

Generating random strings is a frequently used programming technique. Random string are practically everywhere. For example, you may need to generate a random password, e-mail activation code, various keys and so on. Strangely enough, most of the programming languages and development platforms don't have such functionality built-in. Today we'll look how to develop this in PHP. To have a clear target, our goal is to create a function that generates random strings or arbitrary lengths from a predefined character set. We will present you with two different techniques. The first one is simpler to implement and maintain but can be slightly, just slightly slower then the second version.
However, when it comes to a compromise between simplicity, clarity and performance we choose simplicity and clarity. (This does not mean that we ignore performance, however you should not look at performance as is. Rather, you shall view the application as a whole. What do you prefer, a lightning fast payroll application cutting one 0 from your salary from time to time or a slower application printing your salary correctly all the time. This is a topic who may well make a whole book and we promise to publish several posts on code and application quality).

function randomString($length)
{
   // we have a habit to name return value variables as result
   $result = "";

   // predefined character set
   $charset = "abcdefghijklmnopqrstuvwxyz0123456789";

   $i = 0;

   while ($i < $length)
   {
      // pick a random character from the charset
      $char = substr($charset, mt_rand(0, strlen($charset)-1), 1);

      // we generate random string with no repeated characters
      // that's why we reject a character if it's already in the $result
      if (!strstr($result, $char))
      {
         $result .= $char;
         $i++;
      }
    }
   return $result;
}


The second version is almost the same but instead of picking up the characters from a predefined charset string, we get it from a function which takes a random number and returns a character.


function getRandomChar($num)
{
    switch($num)
    {
       case "1":
          return "a";
          break;
       case "2":
          return "b";
          break;
       case "3":
          return "c";
          break;
       case "4":
          return "d";
          break;
       ... // so on for all chars
    }
}



function randomString($length)
{
   $result="";
   if($length>0)
   {
      for($i=1; $i<=$length; $i++)

      {
         $num = mt_rand(1,36);
         $result .= getRandomChar($num);
      } 
   }
   return $result;
}

The second version is slightly faster however it is more complex and less flexible. For example, if you wanted to change the charset (e.g. include new chars like .,# and so on), in the first version you would just add them to the $charset variable. However, with the second version you would have to update the switch construct in the getRandomChar function. So, our preference goes to version one.

1 comments:

Magic No Hair said...
This post has been removed by the author.

Post a Comment