Are you new? Read the FAQ and catch up on!
1k views

Generate random string with PHP

There are a lot of ways to achieve random strings generation, but this is a pretty decent and simple one:

PHP
  1. //
  2.     // Generates a random key with a fixed lenght, passed as parameter.
  3.     // The string may contain any character
  4.     public static function generateRandomKey($length)
  5.     {
  6.         $randstr = "";
  7.         for($i=0; $i<$length; $i++)
  8.         {
  9.             $randnum = mt_rand(0,61);
  10.             if($randnum < 10)
  11.             {
  12.                 $randstr .= chr($randnum+48);
  13.             }
  14.             else if($randnum < 36)
  15.             {
  16.                 $randstr .= chr($randnum+55);
  17.             }
  18.             else
  19.             {
  20.                 $randstr .= chr($randnum+61);
  21.             }
  22.         }
  23.         return $randstr;
  24.     }
  25.  

­

Tags: PHP strings random

Embed: