Creating a unique random string of a certain length and limits in PHP?

I need to create a random 8 character alphanumeric string. Therefore, it should look, for example, as b53m1isM . Both upper and lower case letters and numbers.

I already have a loop that runs eight times, and I want it to concatenate the string with a new random character at each iteration.

Here's the loop:

 $i = 0; while($i < 8) { $randPass = $randPass + //random char $i = $i + 1; } 

Any help?

+7
source share
2 answers
 function getRandomString($length = 8) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $string = ''; for ($i = 0; $i < $length; $i++) { $string .= $characters[mt_rand(0, strlen($characters) - 1)]; } return $string; } 
+22
source
 function randr($j = 8){ $string = ""; for($i=0; $i < $j; $i++){ $x = mt_rand(0, 2); switch($x){ case 0: $string.= chr(mt_rand(97,122));break; case 1: $string.= chr(mt_rand(65,90));break; case 2: $string.= chr(mt_rand(48,57));break; } } return $string; } echo randr(); // b53m1isM 
+1
source

All Articles