This function generates a random string of a specified length. It uses str_shuffle to randomize a string of all alphanumeric characters, then uses substr to get a part of it that’s the desired length. This function is useful for generating random identifiers or tokens.
PHP Function:
function generateRandomString($length = 10) { return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length); }
// Example
echo generateRandomString(5); // 'a3G7s'
echo generateRandomString(10); // '4kU91mBvHq'