I need a valid way to get both a random and unique string, with either a zero (or negligible) chance of a duplicate.
I need characters in the [0-9A-z] range.
This is what I have so far:
substr(sha1(mt_rand().uniqid()),0,22);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Recent changes to PHP
Since I know this is actually talking about bcrypt and password salting now I can really just point people reading this to functions they should be using instead of manually rolling their own salt system.
Use
password_hash($input, PASSWORD_DEFAULT);to generate a hash suitable to insert into a database. This will fetch the salt for you.Insertion:
Verification:
In versions before PHP 5.5, use https://github.com/ircmaxell/password_compat as a drop-in1
When randomly generating a salt, the odds of a collision are
Which for a 22-character string are impossibly low (well, not impossibly, but negligibly)
See? tiny.
Mathematical Fallacy
If you need a truly random string (note: these strings are just a line of numbers mapped to letters), then you’re a little out of luck.
What you’re looking for is a CSPRNG (Cryptographically Secure Pseudo-Random Number Generator). No need for uniqueness.
As @Guarav pointed out in his answer, you can use a timestamp as your seed and then hash it. This is called a UUID (Unique Universal Identifier, if it’s a 128bit timestamp) is predictable, and can be bad for a number of reasons:
Nevertheless, with enough accuracy, you can still use a timestamp as a unique salt. Not random (unless you use it as a random seed and base convert it to base10, which is still a bad idea). Consider this if you can count time in something under nanoseconds and fancy using it as a unique ID. PHP cannot feasibly process fast enough to give two colliding sub-nanosecond IDs1 (but that doesn’t mean you shouldn’t verify!)
1: It works with composer!