suin.io

One-line PHP random string/password generator

suinJuly 31, 2016

This post introduces six ways to generate random strings and passwords in PHP.

1. Using str_shuffle()

  • The same character doesn't appear twice.
  • Maximum length is 36 characters.
function random($length = 8)
{
    return substr(str_shuffle('1234567890abcdefghijklmnopqrstuvwxyz'), 0, $length);
}

2. Using mt_rand()

  • The same character can appear multiple times.
  • Maximum length is 12 characters.
function random($length = 8)
{
    return base_convert(mt_rand(pow(36, $length - 1), pow(36, $length) - 1), 10, 36);
}

3. Using md5() and uniqid()

  • The same character can appear multiple times.
  • Maximum length is 25 characters.
function random($length = 8)
{
    return substr(base_convert(md5(uniqid()), 16, 36), 0, $length);
}

By using sha256 algorithm, maximum length becomes 48 characters.

function random($length = 8)
{
    return substr(base_convert(hash('sha256', uniqid()), 16, 36), 0, $length);
}

4. Using array_reduce()

  • The same character can appear multiple times.
  • Unlimited length.
function random($length = 8)
{
    return array_reduce(range(1, $length), function($p){ return $p.str_shuffle('1234567890abcdefghijklmnopqrstuvwxyz')[0]; });
}

5. Using OpenSSL

  • The same character can appear multiple times.
  • Maximum length is 64 characters.
function random($length = 8)
{
    return substr(base_convert(bin2hex(openssl_random_pseudo_bytes($length)), 16, 36), 0, $length);
}

6. Using str_repeat() and str_shuffle()

  • The same character can appear multiple times.
  • Unlimited length.
function random($length = 8)
{
    return substr(str_shuffle(str_repeat('0123456789abcdefghijklmnopqrstuvwxyz', $length)), 0, $length);
}