Skip to content

Instantly share code, notes, and snippets.

@erikyuntantyo
Last active April 16, 2016 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikyuntantyo/4ffcd4eaaf4a95a8a0c28c449b30a080 to your computer and use it in GitHub Desktop.
Save erikyuntantyo/4ffcd4eaaf4a95a8a0c28c449b30a080 to your computer and use it in GitHub Desktop.
PHP Mongo ObjectId generator
<?php
function generate_object_id() {
$timestamp = str_pad(dechex(time()), 8, "0", STR_PAD_LEFT);
$machine = str_pad(dechex(rand(0, 16777215)), 6, "0", STR_PAD_LEFT);
$pid = str_pad(dechex(rand(0, 32767)), 4, "0", STR_PAD_LEFT);
$increment = rand(0, 16777215);
$increment++;
if ($increment > 0xffffff) {
$increment = 0;
}
$increment = str_pad(dechex($increment), 6, "0", STR_PAD_LEFT);
return $timestamp . $machine . $pid . $increment;
}
<?php
function generate_object_id() {
return dechex(time()) . preg_replace_callback('/[x]/', function($match) {
return dechex((rand() / getrandmax()) * 16);
}, 'xxxxxxxxxxxxxxxx');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment