Posted By

_reydin_ on 06/22/12


Tagged

php random generator String rand


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

_reydin_


Php Random String Generator


 / Published in: PHP
 

This will generate a random alpha numeric string 20 characters long.

  1. <?
  2.  
  3. $l='a'; //Set the starting letter
  4. for($i=0;$i<26;$i++){ //Cycle through all of the letters of the alphabet a-z
  5. $key[$i]=$l; //Load the array with lowercase variables at position $i
  6. $l++; //Increment the letter
  7. }
  8. for($x=0;$x<5;$x++){ //Cycle through this five times. The more you cycle through this loop the more likely a number will appear.
  9. for($n=0;$n<10;$n++){ //Cycle through the numbers 0-9
  10. $key[$i]=$n; //Load the array with number variables at position $i
  11. $i++; //Increment the array key
  12. }
  13. }
  14. $u='A'; //Set the starting letter
  15. for($c=0;$c<26;$c++){ //Cycle through all of the letters of the alphabet A-Z
  16. $key[$i]=$u; //Load the array with uppercase variables
  17. $i++; //Increment the array key
  18. $u++; //Increment the letter
  19. }
  20.  
  21. $i--; //Subtract the last incrementation of $i because it's not indexed
  22.  
  23. $str='';
  24. for($strlength=0;$strlength<20;$strlength++){ //Generate the random string 20 characters long
  25. //$r = rand(0,$i); //Generate a random number from the available $i interger
  26. $r = rand()&$i; //Generate a random number from the available $i interger using bitwise
  27. $str .= $key[$r]; //Concatenate the random variable
  28. }
  29.  
  30. echo $str; //Show the random string
  31. ?>

Report this snippet  

You need to login to post a comment.