Generate random caracters with random case and/or random digits


/ Published in: PHP
Save to your folder(s)

A simple function that generates a string with random alphabet caracters (a to z) and/or digits. Note: the string generated is not guaranteed to be unique.


Copy this code and paste it in your HTML
  1. <?php
  2. /**
  3.  * Function that generates a string with random caracters.
  4.  *
  5.  * $length: The length of the random string.
  6.  *
  7.  * $randomCase: If true, the generated string will also include uppercase alphabet caracters randomly.
  8.  *
  9.  * $includeDigits: If true, the generated string will also include digits randomly.
  10.  */
  11. function random_chars($length = 10, $randomCase = false, $includeDigits = false)
  12. {
  13. $lower = 'abcdefghjkmnpqrstuvwxyz';
  14. $upper = 'ABCDEFGHJKMNPQRSTUVWXYZ';
  15. $digits = '0123456789';
  16. $chars = $lower . ($randomCase ? $upper : '') . ($includeDigits ? $digits : '');
  17. $str = '';
  18.  
  19. $last_index = strlen($chars) - 1;
  20. for($i = 0; $i < $length; $i++)
  21. {
  22. $str .= $chars[mt_rand(0, $last_index)];
  23. }
  24. return $str;
  25. }
  26.  
  27. //How to use
  28. $length = 20;//The string length
  29. //$random_lower: random lowercase alphabet chars, something like: rswcjanzybtaxranszxm
  30. $random_lower = random_chars($length);
  31. //$random_case: random lowercase and uppercase alphabet chars, something like: kTjkvrrejtuArxpNcPJR
  32. $random_case = random_chars($length, true);
  33. //$random_chars_digits: random lowercase and uppercase alphabet chars plus digits, something like: 9GY5KY8Q4wZ81Ge5UvDK
  34. $random_chars_digits = random_chars($length, true, true);
  35.  
  36. echo $random_lower . '<br />';
  37. echo $random_case . '<br />';
  38. echo $random_chars_digits;
  39. ?>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.