PHP Tip, using the uniqid() function

If you have a need for a unique string, consider using PHP’s built in uniqid() function. uniqid() will return a string value based upon the current system time, comprised of both letters and numbers, such as “3e5f173a6d6ed.”

This can be useful in a number of situations:

– Creating unique order IDs
– Generating default passwords
– Naming temporary files

When you call uniqid(), you must pass a string argument, though an empty string (” or “”) is sufficient. If you pass a non-empty string, it will be prepended to the return value. For example,

$fp = fopen(‘/var/tmp/’ . uniqid(‘tmp’) . ‘.file’, ‘wb’);

…would create a resource handle to a file with a name such as “/var/tmp/tmp3e5f2151b0fd0.file.”

The string returned by uniqid() is unique to the microsecond at which it was generated. In other words, if two scripts on your server call uniqid() at the exact same microsecond, they may receive the exact same return value. However, because there are one million microseconds in a second, this degree of uniqueness is more than enough for most applications.

Comments are closed.