Skip to main content

Generate a more truly random alpha-numeric string.

<?php

/**
 * Generate a more truly "random" alpha-numeric string.
 * NOTE: The "random_bytes" built-in function requires PHP v7+.
 * http://php.net/manual/en/function.random-bytes.php
 *
 * @param int $length The length of the string to generate.
 * @return string A random alpha-numeric string of the specified length.
 */
function random($length = 16)
{
    $string = '';

    while (($len = strlen($string)) < $length)
    {
        $size = $length - $len;
        $bytes = random_bytes($size);
        $string .= substr(str_replace([
            '/','+','='
        ], '', base64_encode($bytes)), 0, $size);
    }

    return $string;
}

// ---------------------------------------------------------------------------
// Legacy Support (PHP v5+)
// ---------------------------------------------------------------------------

/**
 * Generate a more truly "random" alpha-numeric string.
 *
 * @param int $length The length of the string to generate.
 * @return string A random alpha-numeric string of the specified length.
 * @throws \RuntimeException
 */
function random_legacy($length = 16)
{
    if (function_exists('openssl_random_pseudo_bytes'))
    {
        $bytes = openssl_random_pseudo_bytes($length * 2);

        if ($bytes === false)
        {
            throw new \RuntimeException('Unable to generate random string.');
        }

        return substr(str_replace(array(
            '/','+','='
        ), '', base64_encode($bytes)), 0, $length);
    }

    return quickRandom($length);
}

/**
 * Generate a "random" alpha-numeric string.
 * Should not be considered sufficient for cryptography, etc.
 *
 * @param int $length The length of the string to generate.
 * @return string A random alpha-numeric string of the specified length.
 */
function quickRandom($length = 16)
{
    $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

    return substr(str_shuffle(str_repeat($pool, 5)), 0, $length);
}

//
// Usage

echo random(32);

?>