-
-
Save ssi-anik/8ad474095b815751585c8f6627065101 to your computer and use it in GitHub Desktop.
A PHP function to generate IDs like MongoDB uses with its ObjectIDs
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 | |
/** | |
* Creating MongoDB like ObjectIDs. | |
* Using current timestamp, hostname, processId and a incremting id. | |
* | |
* @author Julius Beckmann | |
*/ | |
function createMongoDbLikeId($timestamp, $hostname, $processId, $id) | |
{ | |
// Building binary data. | |
$bin = sprintf( | |
"%s%s%s%s", | |
pack('N', $timestamp), | |
substr(md5($hostname), 0, 3), | |
pack('n', $processId), | |
substr(pack('N', $id), 1, 3) | |
); | |
// Convert binary to hex. | |
$result = ''; | |
for ($i = 0; $i < 12; $i++) { | |
$result .= sprintf("%02x", ord($bin[$i])); | |
} | |
return $result; | |
} | |
foreach(range(0, 9) as $id) { | |
var_dump(createMongoDbLikeId(time(), php_uname('n'), getmypid(), $id)); | |
} | |
/* Example output: | |
string(24) "53de1e6d33663012ac000000" | |
string(24) "53de1e6d33663012ac000001" | |
string(24) "53de1e6d33663012ac000002" | |
string(24) "53de1e6d33663012ac000003" | |
string(24) "53de1e6d33663012ac000004" | |
string(24) "53de1e6d33663012ac000005" | |
string(24) "53de1e6d33663012ac000006" | |
string(24) "53de1e6d33663012ac000007" | |
string(24) "53de1e6d33663012ac000008" | |
string(24) "53de1e6d33663012ac000009 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment