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());
}
Answer
Solution:
instead of using current date try using current time stamp that is time()
$hash = md5(rand(0,100000)+strtotime(time())+$row[0]);
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.
Answer
Solution:
add the timestamp to your md5
Answer
Solution:
You're using
date()
wrong.You're adding as numbers instead of concatenating as strings.
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.