Skip to content

Instantly share code, notes, and snippets.

@puncoz
Created May 13, 2018 05:20
Show Gist options
  • Save puncoz/305680d1b1dbf4329f73a57582078838 to your computer and use it in GitHub Desktop.
Save puncoz/305680d1b1dbf4329f73a57582078838 to your computer and use it in GitHub Desktop.
alternative to uniqid() in php
function cryptoUniqid(string $prefix = '', bool $prng = false): string
{
static $nonce = null;
if($prng || is_null($nonce)) {
$nonce = random_bytes(16);
} else {
sodium_increment($nonce);
}
$m = microtime(true);
$return = sprintf("%8x%05x", floor($m), ($m-floor($m))*1000000);
$return = $return . '.' . base64_encode($nonce);
return $prefix . $return;
}
function compat_uniqid(string $prefix='', bool $more_entropy = false)
{
static $nonce = null;
if(is_null($nonce)) {
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
}
$m = microtime(true);
$return = sprintf("%8x%05x",floor($m),($m-floor($m))*1000000);
if($more_entropy) {
sodium_increment($nonce);
$x = hexdec(substr(bin2hex($nonce),0,12));
$return = $return . substr($x, 2, 1) . '.' . substr($x, -8);
}
return $prefix . $return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment