PHP Random String Function

28th January 2011

I was testing a string manipulation function today (which I will post some other time) and I wanted to create a random string of characters that I could feed into it, so I came up with the function below. I thought it was a neat use of the rand() and chr() PHP functions, so here it is.

  1. function random_string($length = 50) {
  2. $string = '';
  3.  
  4. for ($i = 0; $i < $length; ++$i) {
  5.  
  6. $type = rand(1, 5);
  7.  
  8. switch ($type) {
  9. case 1:
  10. // lowercase letters
  11. $ascii_start = 65;
  12. $ascii_end = 90;
  13. break;
  14. case 2:
  15. // uppercase leters
  16. $ascii_start = 97;
  17. $ascii_end = 122;
  18. break;
  19. case 3:
  20. // Space
  21. $ascii_start = 32;
  22. $ascii_end = 32;
  23. break;
  24. case 4:
  25. // numbers
  26. $ascii_start = 48;
  27. $ascii_end = 57;
  28. break;
  29. case 5:
  30. // Punctuation
  31. $ascii_start = 33;
  32. $ascii_end = 47;
  33. break;
  34. }
  35.  
  36. $string .= chr(rand($ascii_start, $ascii_end));
  37. }
  38. return $string;
  39. }

It works by picking a type of character to use (eg, uppercase letter, number etc) and then selecting one at random using the chr() function. The chr() function takes a number as a parameter and will return the ascii character corresponding to that number. For example, given the number 65 the chr() function will return the string 'A'. It will loop over this selection process to build a string.

Here are some examples of the sort of output this function produces.

  1. ye 82 C!4p $$r" lg 3 Ed-W KGrX1% 21V V"mENV YzA B
  2. 1% .AjU C/7 E7 %3uplK g40-'$ i,j% E+JYh Ox AU7I
  3. %q. v$ ,#H5t *d %9Xv59* *oZ3Hj-'G1- 2*7 a+I8Jy& 0
  4. $)V, 7&g6o$3 u27 g" p6 O* eU"LG Th 9J,&3* zH)+*e
  5. &5 u$/l)L0 MZ2'H 1MrymE X h3 66 4AW )WT1f 0 zQtF
  6. - CAc2U'QU*1E5 -MfQ $ HMGJ0xg%,J0 q27r s 4oFz!74"
  7. h Dx.h"Cq1ANF0S- S8w!z%hS x%D8M'O(6a) 3r8H#$#./&i
  8. a .!J (As3a!v&DXK0PIf1$B0JR Pp,KrM (/uUz22gm S% ,-
  9. *5j$,%0+ VSsz,a0oA7)' s9J$5/ R"iK3cvz GDQn3DC'"lc
  10. 6 xK,r2 R/1Y"y46S& s39#US p*h1+2R8,0yr6 -HYG 'N"

 

Add new comment

The content of this field is kept private and will not be shown publicly.