Skip to content

Instantly share code, notes, and snippets.

@thinkt4nk
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkt4nk/9495153 to your computer and use it in GitHub Desktop.
Save thinkt4nk/9495153 to your computer and use it in GitHub Desktop.
Random Confirm Code Generator
<?
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