-
-
Save muhamed-didovic/006af76c8719ccb762f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
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