php - MD5 random generate code duplicate

138

I'm using md5 with random code, current datetime and customer_id to generate a hash code but after I run 200,000 records I found there is many duplicated records. How can i avoid the duplicate?

while ($row = mysql_fetch_array($result, MYSQL_NUM)) {

$curr_date = date('Y-m-d H:i:s');
$hash = md5(rand(0,100000)+strtotime(date('curr_date'))+$row[0]);

echo $query = "update customers set email_hash='$hash' where customer_id='$row[0]'";
mysql_query($query) or die(mysql_error());
}
539

Answer

Solution:

instead of using current date try using current time stamp that is time()

$hash = md5(rand(0,100000)+strtotime(time())+$row[0]);

755

Answer

Solution:

The problem is that the time could be the same for up to thousands of your entries, as you are only taking the time up to the seconds. You could try to use the milliseconds and nanoseconds as well, or sleep between two generations.

But in any way it would be safer to use another hashing algorithm with more bits spent to hash, that way collisions are less probable.

316

Answer

Solution:

add the timestamp to your md5

$hash = md5(rand(0,100000)+strtotime(date('curr_date'))+$row[0])."_".time();
47

Answer

Solution:

  1. You're usingdate() wrong.

    date('c')
    
  2. You're adding as numbers instead of concatenating as strings.

    rand(0,100000) . strtotime(date('c')) . $row[0]
    

As it is you're using only a very small number of possible plaintexts for the hash. Fixing these two issues will reduce the number of collisions drastically.

People are also looking for solutions to the problem: javascript - Jcrop not cropping the selected area on Large Images

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.