Skip to content

Instantly share code, notes, and snippets.

@jblac
Created September 22, 2014 20:09
Show Gist options
  • Save jblac/99a4984720b01c546f59 to your computer and use it in GitHub Desktop.
Save jblac/99a4984720b01c546f59 to your computer and use it in GitHub Desktop.
<?php
class generateToken {
public function crypto_rand_secure($min, $max) {
$range = $max - $min;
if ($range < 0 ) { return $min; }
$log = log($range, 2);
$bytes = (int) ( $log / 8 ) + 1;
$bits = (int) $log + 1;
$filter = (int) ( 1 << $bits ) -1;
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
$rnd = $rnd & $filter;
} while ( $rnd >= $range );
return $min + $rnd;
}
public function generateToken($length) {
$token = '';
$codeAlphabet = "abcdefghijklmnopqrstuvwxyz";
$codeAlphabet .= "0123456789";
for ($i=0; $i < $length; $i++) {
$token .= $codeAlphabet[$this->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