Last active
August 29, 2015 13:57
-
-
Save thinkt4nk/9495153 to your computer and use it in GitHub Desktop.
Random Confirm Code Generator
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
<? | |
class confirm_code | |
{ | |
protected static function generate_random_bytes($length=16){ | |
if(function_exists('openssl_random_pseudo_bytes')) { | |
$rnd = openssl_random_pseudo_bytes($length, $strong); | |
if ($strong === TRUE) | |
return $rnd; | |
} | |
$rand = ''; | |
// Unix/Linux platform? | |
$fp = @fopen('/dev/urandom','rb'); | |
if ($fp === FALSE) | |
throw new Exception("No method for generating random bytes"); | |
$rand .= @fread($fp,$length); | |
@fclose($fp); | |
return $rand; | |
} | |
public static function create($length=6) | |
{ | |
$keyspace = '0123456789'; | |
$entropy = self::generate_random_bytes($length); | |
$entropy = str_split($entropy); | |
$callback = function($str) { | |
return ord($str); | |
}; | |
$entropy_list = array_map($callback, $entropy); | |
$confirm_code = ""; | |
foreach ($entropy_list as $value) | |
$confirm_code .= $keyspace[($value % 10)]; | |
return $confirm_code; | |
} | |
} | |
// test | |
/* | |
for ($i=0; $i < 10; $i++) | |
{ | |
printf("\n%s", confirm_code::create()); | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment