Skip to content

Instantly share code, notes, and snippets.

@muhamed-didovic
Forked from h4cc/createMongoDbLikeId.php
Last active October 22, 2021 06:48
Show Gist options
  • Save muhamed-didovic/006af76c8719ccb762f1 to your computer and use it in GitHub Desktop.
Save muhamed-didovic/006af76c8719ccb762f1 to your computer and use it in GitHub Desktop.
<?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
*/
@Abylaikhan
Copy link

It is bad solution, if you use it in loop, big probability this method return not unique value, because process Id and time() will not changed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment