diff --git a/lib.php b/lib.php new file mode 100644 index 0000000..d677844 --- /dev/null +++ b/lib.php @@ -0,0 +1,45 @@ + + * @link https://github.com/matiboux/Time-Based-Random-UUID + * @version 1.0 + * @return string Returns the generated UUID. + */ +function uuid($tp = null) { + if(!empty($tp)) { + if(is_array($tp)) $time = ($tp['sec'] * 10000000) + ($tp['usec'] * 10); + else if(is_numeric($tp)) $time = (int) ($tp * 10000000); + else return false; + } else $time = (int) (gettimeofday(true) * 10000000); + $time += 0x01B21DD213814000; + + $arr = str_split(dechex($time & 0xffffffff), 4); // time_low (32 bits) + $high = intval($time / 0xffffffff); + array_push($arr, dechex($high & 0xffff)); // time_mid (16 bits) + array_push($arr, dechex(0x4000 | (($high >> 16) & 0x0fff))); // Version (4 bits) + time_high (12 bits) + + // Variant (2 bits) + Cryptographically Secure Pseudo-Random Bytes (62 bits) + if(function_exists('random_bytes')) $random = random_bytes(8); + else $random = openssl_random_pseudo_bytes(8); + $random[0] = chr(ord($random[0]) & 0x3f | 0x80); // Apply variant: Set the two first bits of the random set to 10. + + $uuid = vsprintf('%s%s-%s-%s-%s-%s%s%s', array_merge($arr, str_split(bin2hex($random), 4))); + return strlen($uuid) == 36 ? $uuid : false; +} +?> \ No newline at end of file diff --git a/test.php b/test.php new file mode 100644 index 0000000..fedc357 --- /dev/null +++ b/test.php @@ -0,0 +1,7 @@ + \ No newline at end of file