Skip to content

Instantly share code, notes, and snippets.

@ssi-anik
Forked from h4cc/createMongoDbLikeId.php
Created November 1, 2019 15:35
Show Gist options
  • Save ssi-anik/8ad474095b815751585c8f6627065101 to your computer and use it in GitHub Desktop.
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
<?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