Created
January 11, 2018 19:42
-
-
Save nachodd/be44b3670a6ef390a67412ae16e5470c to your computer and use it in GitHub Desktop.
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
<?php | |
class helpers { | |
public function uniqueCode($length = 10) { | |
$characters = '0123456789'; | |
$charactersLength = strlen($characters); | |
while (true) { | |
// uniqid gives 13 chars, but you could adjust it to your needs. | |
if (function_exists("random_bytes")) { | |
$bytes = random_bytes($length); | |
} elseif (function_exists("openssl_random_pseudo_bytes")) { | |
$bytes = openssl_random_pseudo_bytes($length); | |
} else { | |
throw new Exception("no cryptographically secure random function available"); | |
} | |
$code = ''; | |
for ($i = 0; $i < $length; $i++) { | |
$code .= $characters[ord($bytes[$i]) % $charactersLength]; | |
} | |
// check uniqueness by querying the DB | |
//if (!$this->checkTicketCodeUniqueness($code)){ | |
// break; | |
//} | |
} | |
return $code; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment