Generating Unique ID’s in PHP

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

unique

// 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:

// 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
*/

This function will generate shorter strings than md5(), which will also save you some space.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s