Use the ASCII table to pick a range of letters, where the: $range_start , $range_end is a value from the decimal column in the ASCII table.
I find that this method is nicer compared to the method described where the range of characters is specifically defined within another string.
// range is numbers (48) through capital and lower case letters (122)
$range_start = 48;
$range_end = 122;
$random_string = "";
$random_string_length = 10;
for ($i = 0; $i < $random_string_length; $i++) {
$ascii_no = round( mt_rand( $range_start , $range_end ) ); // generates a number within the range
// finds the character represented by $ascii_no and adds it to the random string
// study **chr** function for a better understanding
$random_string .= chr( $ascii_no );
}
echo $random_string;
Generate cryptographically strong, random (potentially) 8-character string using the openssl_random_pseudo_bytes function:
echo bin2hex(openssl_random_pseudo_bytes(4));
Procedural way:
function randomString(int $length): string
{
return bin2hex(openssl_random_pseudo_bytes($length));
}
Update:
PHP7 introduced the random_x() functions which should be even better. If you come from PHP 5.X, use excellent paragonie/random_compat library which is a polyfill for random_bytes() and random_int() from PHP 7.
function randomString($length)
{
return bin2hex(random_bytes($length));
}
If you want a very easy way to do this, you can lean on existing PHP functions. This is the code I use:
substr( sha1( time() ), 0, 15 )
time() gives you the current time in seconds since epoch, sha1() encrypts it to a string of 0-9a-f, and substr() lets you choose a length. You don't have to start at character 0, and whatever the difference is between the two numbers will be the length of the string.
Simple guys .... but remember each byte is random between 0 and 255 which for a random string will be fine. Also remember you'll have two characters to represent each byte.
$str = bin2hex(random_bytes(32)); // 64 character string returned