Showing posts with label md5(). Show all posts
Showing posts with label md5(). Show all posts

Wednesday 1 August 2012

PHP Unique ID's


Generating Unique ID's

 Many of us use the md5() function for this, even though it's not exactly meant for this purpose:
// 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();

// Output like this:

4bd67c947233e

// generate another unique string
echo uniqid();

// Output like this:

4bd67c9472340.

To reduce the chances of getting a duplicate, you can pass a prefix, or the second parameter to increase entropy:
// with prefix
echo uniqid('myname_');

// Output like this:

myname_4bd67d6cd8b8f


// with more entropy
echo uniqid('',true);

// Output like this:

4bd67d6cd8b926.12135106


// both
echo uniqid('myname_',true);

// Output like this:

myname_4bd67da367b650.43684647