Skip to content

Instantly share code, notes, and snippets.

@nicklasos
Created July 2, 2014 12:56
Show Gist options
  • Save nicklasos/199dbab3c8c3c862b479 to your computer and use it in GitHub Desktop.
Save nicklasos/199dbab3c8c3c862b479 to your computer and use it in GitHub Desktop.
Mongo id from time
<?php
function mongo_id_from_time($yourTimestamp)
{
static $inc = 0;
$ts = pack('N', $yourTimestamp);
$m = substr(md5(gethostname()), 0, 3);
$pid = pack('n', posix_getpid());
$trail = substr(pack('N', $inc++), 1, 3);
$bin = sprintf("%s%s%s%s", $ts, $m, $pid, $trail);
$id = '';
for ($i = 0; $i < 12; $i++ ) {
$id .= sprintf("%02X", ord($bin[$i]));
}
return new \MongoID($id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment