Last active
April 17, 2018 15:57
-
-
Save vaibhavhrt/1a9c82c45fc1262adaa12c851a2eac15 to your computer and use it in GitHub Desktop.
Generate a random token. From: https://stackoverflow.com/questions/3290283/what-is-a-good-way-to-produce-a-random-site-salt-to-be-used-in-creating-passwo/3291689#3291689
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
$x = getToken(); | |
echo $x; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment