ElggCrypto::getRandomString PHP Method

getRandomString() public method

Uses supplied character list for generating the new string. If no character list provided - uses Base64 URL character set.
See also: https://github.com/zendframework/zf2/blob/master/library/Zend/Math/Rand.php#L179
public getRandomString ( integer $length, string | null $chars = null ) : string
$length integer Desired length of the string
$chars string | null Characters to be chosen from randomly. If not given, the Base64 URL charset will be used.
return string The random string
    public function getRandomString($length, $chars = null)
    {
        if ($length < 1) {
            throw new \InvalidArgumentException('Length should be >= 1');
        }
        if (empty($chars)) {
            $numBytes = ceil($length * 0.75);
            $bytes = $this->getRandomBytes($numBytes);
            $string = substr(rtrim(base64_encode($bytes), '='), 0, $length);
            // Base64 URL
            return strtr($string, '+/', '-_');
        }
        if ($chars == self::CHARS_HEX) {
            // hex is easy
            $bytes = $this->getRandomBytes(ceil($length / 2));
            return substr(bin2hex($bytes), 0, $length);
        }
        $listLen = strlen($chars);
        if ($listLen == 1) {
            return str_repeat($chars, $length);
        }
        $bytes = $this->getRandomBytes($length);
        $pos = 0;
        $result = '';
        for ($i = 0; $i < $length; $i++) {
            $pos = ($pos + ord($bytes[$i])) % $listLen;
            $result .= $chars[$pos];
        }
        return $result;
    }

Usage Example

Example #1
0
/**
 * Initialise the site secret (32 bytes: "z" to indicate format + 186-bit key in Base64 URL).
 *
 * Used during installation and saves as a datalist.
 *
 * Note: Old secrets were hex encoded.
 *
 * @return mixed The site secret hash or false
 * @access private
 * @todo Move to better file.
 */
function init_site_secret()
{
    $secret = 'z' . ElggCrypto::getRandomString(31);
    if (datalist_set('__site_secret__', $secret)) {
        return $secret;
    }
    return FALSE;
}
All Usage Examples Of ElggCrypto::getRandomString