Friday, 19 September 2014

PHP: Create big unique ID like Facebook or MongoDB

Most of web application using a relational database management system (MSQL, SQL ..etc) to store data as records. We need an unique id to use as a key Primary.
How to do it ?
* SQL AUTO INCREMENT a Field :
--> 1,2,3,4,5..... #anyone can count the number of your records and more

* PHP uniqid :
--> 541cf7f7d685e, 541cf7f7d685e, 541cf7f7d685e .....  #somewhat similar?

* Or use a custom function like this :

function gen_id() {
    return sprintf( '%04x%04x%04x%04x%04x%04x%04x%04x',
        // 32 bits for "time_low"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

        // 16 bits for "time_mid"
        mt_rand( 0, 0xffff ),

        // 16 bits for "time_hi_and_version",
        // four most significant bits holds version number 4
        mt_rand( 0, 0x0fff ) | 0x4000,

        // 16 bits, 8 bits for "clk_seq_hi_res",
        // 8 bits for "clk_seq_low",
        // two most significant bits holds zero and one for variant DCE1.1
        mt_rand( 0, 0x3fff ) | 0x8000,

        // 48 bits for "node"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
}
Result : 6800cd499f25434aac48c0bb51f46307, caa02c4831194690ad8458c3a4e07a0c, 7488a4c459d64f8dbacd2b79f44ed4bf ......

- differences
- professional (like facebook, google, MongoDB ...)
high performance
- unrestricted

Reference : PHP uuid lib

0 nhận xét:

Post a Comment