Last active
August 19, 2020 08:17
-
-
Save szabacsik/bf085ecf83683898ae3bd534d30c35bb to your computer and use it in GitHub Desktop.
Unique Token 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
<?php | |
class Token | |
{ | |
public static function generate() | |
{ | |
$microtime = microtime(true); | |
$microtimeString = (string)number_format($microtime, 6, '.', ''); | |
if (!strpos($microtimeString, '.')) | |
$microtimeString = $microtimeString . '.0'; | |
$now = \DateTime::createFromFormat('U.u', $microtimeString); | |
$now->setTimezone(new \DateTimeZone('Europe/Budapest')); | |
$datetime = $now->format("Ymd-His-u"); | |
$bytes = openssl_random_pseudo_bytes(8); | |
return md5($datetime) . bin2hex($bytes); | |
} | |
} | |
echo Token::generate(); | |
exit; | |
//TEST | |
$tokens = []; | |
for ($i = 0; $i < 50000; $i++) { | |
$token = Token::generate(); | |
if (!in_array($token, $tokens)) | |
$tokens[] = $token; | |
else | |
die('UNIQUE ERROR' . PHP_EOL); | |
if (strlen($token) != 48) | |
die('LENGTH ERROR' . PHP_EOL); | |
} | |
echo 'OK' . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment