Monday, 24 November 2014

PHP random string generation

Generating random strings can be very useful in lot of cases. You can generate random passwords, a validation codes and so on. The main points in random string generation are the followings:
  • Define the valid characters can be used in the string
  • Define the length of the string
  • Generating a random number
So after you have a list of the usable characters then you need to select one of them randomly and add it to a result string. Repeat it until the length of the result string is sufficient.

To define the valid characters simple use a string and initialize it with the allowed characters like this:
Code:
  1. $validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ+-*#&@!?";

The length of the requested string can be an input parameter of the function.

To get a random character from our list we need to use a random number generator function. In PHP there are more possibilities. The original rand() function is slow and it's algorithm is not as good as the newer mt_rand() so we use mt_rand(). As parameter we can define a minimum and a maximum value so the generated number will be between these values. For example if you want to generate random numbers between 0 and 10 then you can do it like this:

Code:
  1. $index = mt_rand(0, 10);
  2.  
  3. echo $index;

In our case the minimum value is 0 and the maximum value is the length of the valid string variable minus one. This is because we handle the string as an array and the first index of the array is 0. Accordingly selecting one random character from the valid character list is the following:

Code:
  1. $validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ+-*#&@!?";
  2. $validCharNumber = strlen($validCharacters);
  3.  
  4. $index = mt_rand(0, $validCharNumber-1);
  5. $randomCharacter = $validCharacters[$index];
  6.  
  7. echo $randomCharacter;

What we need next is to surround this code with a loop to generate the string with the requested length:

Code:
  1. $length = 5;
  2. $result = "";
  3.  
  4. for ($i = 0; $i < $length; $i++) {
  5.     $index = mt_rand(0, $validCharNumber-1);
  6.     $result .= $validCharacters[$index];
  7. }

Finally we can put it all together in a simple function as here:

Code:
  1. function getRandomString($length = 6) {
  2.     $validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ+-*#&@!?";
  3.     $validCharNumber = strlen($validCharacters);
  4.  
  5.     $result = "";
  6.  
  7.     for ($i = 0; $i < $length; $i++) {
  8.         $index = mt_rand(0, $validCharNumber - 1);
  9.         $result .= $validCharacters[$index];
  10.     }
  11.  
  12.     return $result;
  13. }
  14.  
  15. echo getRandomString();

0 comments:

Post a Comment