Created
March 9, 2018 13:57
-
-
Save lokielse/c7244c16fb7778f78f660a06b3c3119b to your computer and use it in GitHub Desktop.
Generate an ID string that form 24 hexidecimal characters, just like a MongoId string.
This file contains hidden or 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 | |
/** | |
* File: generate_id_hex.php | |
* Author: Alvan | |
* Modifier: Alvan | |
* Modified: 2014-03-28 | |
*/ | |
error_reporting(E_ALL); | |
ini_set('display_errors', 'on'); | |
date_default_timezone_set('UTC'); | |
/** | |
* Generate an ID, constructed using: | |
* a 4-byte value representing the seconds since the Unix epoch, | |
* a 3-byte machine identifier, | |
* a 2-byte process id, and | |
* a 3-byte counter, starting with a random value. | |
* Just like a MongoId string. | |
* | |
* @link http://www.luokr.com/p/16 | |
* @link http://docs.mongodb.org/manual/reference/object-id/ | |
* @return string 24 hexidecimal characters | |
*/ | |
function generate_id_hex() | |
{ | |
static $i = 0; | |
$i OR $i = mt_rand(1, 0x7FFFFF); | |
return sprintf("%08x%06x%04x%06x", | |
/* 4-byte value representing the seconds since the Unix epoch. */ | |
time() & 0xFFFFFFFF, | |
/* 3-byte machine identifier. | |
* | |
* On windows, the max length is 256. Linux doesn't have a limit, but it | |
* will fill in the first 256 chars of hostname even if the actual | |
* hostname is longer. | |
* | |
* From the GNU manual: | |
* gethostname stores the beginning of the host name in name even if the | |
* host name won't entirely fit. For some purposes, a truncated host name | |
* is good enough. If it is, you can ignore the error code. | |
* | |
* crc32 will be better than Times33. */ | |
crc32(substr((string)gethostname(), 0, 256)) >> 8 & 0xFFFFFF, | |
/* 2-byte process id. */ | |
getmypid() & 0xFFFF, | |
/* 3-byte counter, starting with a random value. */ | |
$i = $i > 0xFFFFFE ? 1 : $i + 1 | |
); | |
} | |
/** | |
* test: | |
* php generate_id_hex.php | grep -i "Duplicated!" | wc -l | |
*/ | |
$table = array(); | |
for ($i = 0; $i < 100000; $i++) | |
{ | |
$_ = generate_id_hex(); | |
var_dump($_); | |
if (isset($table[$_])) | |
{ | |
$table[$_] += 1; | |
var_dump('Duplicated!'); | |
} | |
else | |
{ | |
$table[$_] = 1; | |
} | |
} | |
// End of file : generate_id_hex.php |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment