Skip to content

Instantly share code, notes, and snippets.

@nachodd
Created January 11, 2018 19:42
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 nachodd/be44b3670a6ef390a67412ae16e5470c to your computer and use it in GitHub Desktop.
Save nachodd/be44b3670a6ef390a67412ae16e5470c to your computer and use it in GitHub Desktop.
<?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