Skip to content

Instantly share code, notes, and snippets.

@Nicksxs
Created July 30, 2015 09:22
Show Gist options
  • Save Nicksxs/e0f914a0a7c5e1df5f71 to your computer and use it in GitHub Desktop.
Save Nicksxs/e0f914a0a7c5e1df5f71 to your computer and use it in GitHub Desktop.
<?php
function crypto_rand_secure($min, $max)
{
$range = $max - $min;
if ($range < 0) return $min; // not so random...
$log = 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=32){
$token = "";
$codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$codeAlphabet.= "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet.= "0123456789";
for($i=0;$i<$length;$i++){
$token .= $codeAlphabet[crypto_rand_secure(0,strlen($codeAlphabet))];
}
return $token;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment