In this article we will see how to generate a random hash string using php.

We can use the rand() or mt_rand() functions to generate random integers that correspond to ASCII codes, and then convert those integers to characters.

Following is an example PHP program to generate the random strings of the specified length.

function randomHash($format, $length) {
  $pool = "";

  switch ($format) {
    case "alnum":
      $pool = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      break;
    case "alpSpecLower":
      $pool = "abcdefghijklmnopqrstuvwxyz-_";
      break;
    case "alpha":
      $pool = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
      break;
    case "alpNumLower":
      $pool = "0123456789abcdefghijklmnopqrstuvwxyz";
      break;
    case "hexdec":
      $pool = "0123456789abcdef";
      break;
    case "numeric":
      $pool = "0123456789";
      break;
    case "nozero":
      $pool = "123456789";
      break;
    default:
      return "";
  }

  $str = "";

  for ($i = 0; $i < $length; $i++) {
    $index = rand(0, strlen($pool) - 1);
    $str .= $pool[$index];
  }

  return $str;
}

Explanation

In the above example, we define a $pool for each format which contains the characters that are used to generate the random string.

The appropriate format can be selected by using the switch statement.

Using the rand() function, we generate a random index in the range of $pool array and append the corresponding character to the $str string. Finally, the $str contains the randomly generated string with the desired format.

We call the randomHash() function with the desired format to generate the random string. Following is the example:

echo "alnum: " . randomHash("alnum", 10) . "\n";
echo "alpSpecLower: " . randomHash("alpSpecLower", 10) . "\n";
echo "alpha: " . randomHash("alpha", 10) . "\n";
echo "alpNumLower: " . randomHash("alpNumLower", 10) . "\n";
echo "hexdec: " . randomHash("hexdec", 10) . "\n";
echo "numeric: " . randomHash("numeric", 10) . "\n";
echo "nozero: " . randomHash("nozero", 10) . "\n";

Categorized in:

Tagged in: