Uniqid() – The easiest way to generate unique strings

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 secuirty hazard and should never be used to generate a security token. However, there is another function mt_rand() which generates better random value.

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

[php]
<?php
echo uniqid();
?>
[/php]

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

[php]
<?php
echo uniqid("prefix_");
?>
[/php]

which will generate “prefix_4f3cb635538ed”

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

[php]
<?php
echo md5(uniqid());
?>
[/php]

Similarly, you can get 40 character using sha1
[php]
<?php
echo sha1(uniqid());
?>
[/php]

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

[php]<?php
echo md5(uniqid(mt_rand(), true));
?>
[/php]

Returns a string similar to “4ef2854881f4cd9bdd84081477bc3317”

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

Leave a Reply

Your email address will not be published. Required fields are marked *