Generate a Random String of any length

Description PHP

This function returns a string of $nSize, of completely random characters and/or numbers.

This can be useful for assigning unique identifiers or for encryption keys.

The Code Download

  1. <?php
  2. function GetSID ($nSize=24) {
  3.     // Randomize
  4.     mt_srand ((double) microtime() * 1000000);
  5.     for ($i=1; $i<=$nSize; $i++) {
  6.         $nRandom = mt_rand(1,30);
  7.         if ($nRandom <= 10) {
  8.             // Uppercase letters
  9.             $sid .= chr(mt_rand(65,90));
  10.         } elseif ($nRandom <= 20) {
  11.             // Numbers
  12.             $sid .= mt_rand(0,9);
  13.         } else {
  14.             // Lowercase letters
  15.             $sid .= chr(mt_rand(97,122));
  16.         }
  17.     }
  18.     return $sid;
  19. }
  20. ?>

Credits

Added by JC on 14th January 2008

Comments

There are no comments about this snippet.

Post Comment Github Markdown Supported

You must be logged in to post a comment.

Login here to post a comment