uniqid()
Sometimes we need a string of random characters to ensure a unique filename for instance. In the past I’ve seen scripts use time() or even a number of rand() calls in a row to generate a string.
No need to go through all of that because once again, there’s a function for that.
This function creates a fourteen character string based on the current time in microseconds. Since it’s based on microseconds, even two calls of uniqid() one right after the other will generate two distinct strings.
You can also optionally have the function prepend a string you pass as a parameter. This prefix is limited to 114 characters max.
For additional entropy (more randomness), set the second parameter to true. This will append ten more characters to the string.
// Due to the nature of this function, // the following output is example only echo uniqid(); // 497fd828ce3a7 echo uniqid(); // 497fd828ce3ca echo uniqid("qwerty_"); // qwerty_497fd828ce3d6 echo uniqid("qwerty_", true); // qwerty_497fd828ce3e13.18242353 echo uniqid("", true); // 497fd828ce3f36.86308612
Don’t rely on this function for security. It isn’t meant to be a completely random string, just a string that’s guaranteed not to be the same as any created previously from the function.
And remember, this is not uniqueid, it’s uniqid().
