Generator random string with PHP

PHP Jul 13, 2020 Viewed 25 Comments 0

Two ways to generate random strings using PHP.

1. With rand method

function generateRandomString($length = 10)
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

Use it.

// generates 4 length of string
echo generateRandomString(4)

2. With str_shuffle method

The function of str_shuffle() does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int()random_bytes(), or openssl_random_pseudo_bytes() instead.

function generateRandomString($length = 10)
{
    return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
}

Use it

echo generateRandomString(4);
Updated Jul 13, 2020