PHP – Generate a Random String with A-Z and 0-9

This example shows you how to generate a random string with A-Z and 0-9 using the str_shuffle built-in PHP function, which lets us shuffle a string randomly.

function generateRandomString($length = 20) {
    $randomString = str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
    return substr($randomString, 0, $length);

Use the function:

echo generateRandomString(); // QyxEVhdFZkGI7pB1UCRi
echo generateRandomString(10); // eSVzyOTvCu
echo generateRandomString(30); // hoNwLAV35Ux8EISYd7qZ6OmjiJsGuD