How to Generate a Random String in PHP?

Problem:

You want to generate a random string that is 15 characters long(or any other length).

Solution:

There are few ways you can generate random string. Here you’ll use a easy method to generate a random string.

The following code will generate a 15 characters long random string.

<?php
$rand_str = "";
$str_length = 15;
for($i=0; $i<$str_length; $i++){
    $rand_number = mt_rand(0,51);
    $string = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
    $rand_str .= substr($string, $rand_number, 1);
}
echo $rand_str;
?>

[wpdm_file id=88]

Output:
waKmrDTcVIXxoKY

How it works:

Line 3 $str_length variable is assigned to 15 which is the length of our random string. If you want to generate a random string of different length, replace 15 by the that number.
Line 4-8 The for loop will run 15 times(which is the length of the random string) and each time it will pick a random character from the 52 characters stored in the $string variable (line 6).
Line 5 Function mt_rand() will generate a random number between 0 and 51. We use (0 to 51) as there are in total 52 characters in the $string variable and we want to pick one character randomly using whose position is same as the random number $rand_number.
Line 7 Now, we’ll pick one character whose position number generated by the mt_rand() function in line 5.
substr() function returns part of a string. Here, the function returns 1 character(specified by the third parameter) starting from the $rand_number position(specified by the second parameter) from the $string string (specified by the first parameter).
Line 9 Displays the random number.