Posted By

jjjrmy on 08/15/10


Tagged

random String generate genrandomstring


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

stamba


Generate Random String


 / Published in: PHP
 

I didn't make this, I just found it online and found it really useful for generating unique IDs for stuff.

Have fun using this.

  1. function genRandomString($length) {
  2. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  3. $string = '';
  4. for ($p = 0; $p < $length; $p++) {
  5. $string .= $characters[mt_rand(0, strlen($characters))];
  6. }
  7. return $string;
  8. }
  9.  
  10. //////////////////////////////////////
  11. // Example : //
  12. // //
  13. // echo genRandomString(rand(3,7)); //
  14. // //
  15. // Could Print Out: Ac1dF //
  16.  
  17. //////////////////////////////////////

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Sverri on August 16, 2010

There is no reason to use a loop. Just shuffle the string and take out the segment you need.

function str_rand($len=10) {
  $shuffled = str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
  return substr($shuffled, 0, $len);
}
Posted By: stamba on December 23, 2010

I have tested this code to generate 404 32-chars long strings. Lengths of the strings are between 30 and 33 chars. Code that Sverri posted works like a charm! I got all unique strings and they were all 32 chars long.

You need to login to post a comment.