• How To Generating Unique ID’s in PHP

    Generate Unique IDThere may be situations where you need to generate a unique string. I
    have seen many people use the md5() function for this, even though it’s not exactly meant for this purpose:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    
    // generate unique string
     
    echo md5(time() . mt_rand(1,1000000));
     
    There is actually a PHP function named uniqid() that is meant to be used
     
    for this.
     
    // generate unique string
     
    echo uniqid();
     
    /* prints
     
    4bd67c947233e
     
    */
     
    // generate another unique string
     
    echo uniqid();
     
    /* prints
     
    4bd67c9472340
     
    */

    You may notice that even though the strings are unique, they seem

    similar for the first several characters. This is because the generated

    string is related to the server time. This actually has a nice side

    effect, as every new generated id comes later in alphabetical order, so

    they can be sorted.

    To reduce the chances of getting a duplicate, you can pass a prefix, or

    the second parameter to increase entropy:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    
    // with prefix
     
    echo uniqid('foo_');
     
    /* prints
     
    foo_4bd67d6cd8b8f
     
    */
     
    // with more entropy
     
    echo uniqid('',true);
     
    /* prints
     
    4bd67d6cd8b926.12135106
     
    */
     
    // both
     
    echo uniqid('bar_',true);
     
    /* prints
     
    bar_4bd67da367b650.43684647
     
    */

Comments on this post

Leave a Reply

  • Security Code :


    two × = 18