Skip to content

Instantly share code, notes, and snippets.

@RobertoNovelo
Created October 6, 2015 14:15
Show Gist options
  • Save RobertoNovelo/bcb6fa3fa4d18d067117 to your computer and use it in GitHub Desktop.
Save RobertoNovelo/bcb6fa3fa4d18d067117 to your computer and use it in GitHub Desktop.
Random, unique, alphanumeric string with defined length
function crypto_rand_secure($min, $max)
{
$range = $max - $min;
if ($range < 1) return $min; // not so random...
$log = ceil(log($range, 2));
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd >= $range);
return $min + $rnd;
}
function getToken($length)
{
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
$max = strlen($codeAlphabet) - 1;
for ($i=0; $i < $length; $i++) {
$token .= $codeAlphabet[crypto_rand_secure(0, $max)];
}
return $token;
}
//from http://stackoverflow.com/a/13733588/1550485
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment