Skip to content

Instantly share code, notes, and snippets.

@h4cc
Created August 3, 2014 11:37
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save h4cc/9b716dc05869296c1be6 to your computer and use it in GitHub Desktop.
Save h4cc/9b716dc05869296c1be6 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