Uniqid() – The easiest way to generate unique words

I have seen many PHP developers still use rand() for generating security tokens/unique strings, mostly for generating validation strings such as Email validation etc

rand() is a security hazard and should never be used to generate a security token. However, there is another function mt_rand() which generates a better random value.

What if you want to generate a quick and dirty random string for your program? Try uniqid()

echo uniqid();

The above code will output a string such as “4f3cb635538ed”. If you execute it again, you will get another string. If you want to include a prefix, you can use this

echo uniqid("prefix_");

which will generate “prefix_4f3cb635538ed”

If you need 32 character string, you can md5 the random value

echo md5(uniqid());

Similarly, you can get 40 character using sha1

echo sha1(uniqid());

A combination of these all will give you some more powerful unique string. For most security purposes this is a good token

echo md5(uniqid(mt_rand(), true));

Returns a string similar to “4ef2854881f4cd9bdd84081477bc3317”

2 thoughts on “Uniqid() – The easiest way to generate unique words

Leave a Reply

Your email address will not be published.