在php中生成一个唯一值[重复]

This question already has an answer here:

I am considering options to use in generating a 5 character unique string in php. Or if anyone have a better option. I'm not sure if substr will actually reduces the reliability of the uniqueness as well. All advise appreciated.

Option1:

$unique_id=substr(md5(time()), -5);

OR

Option2:

$unique_id=substr(uniqid, -5);
</div>

This In built php function could help you.

rand(min,max);

Personally I would go with first option, but instead use something more like:

md5(uniqid(rand(), true))

Use, as @Sagar said, the

rand(min,max);

Then store the values in a database. Before you're giving the users the random number, check if it already exists in the database. If it doesn't, move on and insert to the database.

Something like this:

$rand = rand(min,max);

    $sql = "SELECT randomNum FROM users WHERE randomNum = '$rand'";
    $result = mysql_query($sql);
    $count = mysql_num_rows($result);

    if ($count != 1){
        //insert to database
    }