-1

I'm trying to generate a process in order to create aproximately 5000 unique keys into a table with rand_md5 function. Sometimes it is giving a repeated "unique" key constraint violation. What can I do to solve this?

function rand_md5($length) {
  $max = ceil($length / 32);
  $random = '';
  for ($i = 0; $i < $max; $i ++) {
    $random .= md5(microtime(true).mt_rand(10000,90000));
  }
return substr($random, 0, $length);

This function is called inside a for loop from 1 to 5000 iterations (for example).

Any ideas how to solve this?

John Cartwright
  • 5,109
  • 22
  • 25
Rodolfo Velasco
  • 845
  • 2
  • 12
  • 27
  • http://stackoverflow.com/questions/1155008/how-unique-is-uuid – anonymous May 13 '15 at 16:03
  • 2
    So don't generate unique stuff using PHP, just use MySQL for that. `INSERT INTO table (my_unique_column) values (MD5(UUID());` and there you go, unique. No language should have the authority for generating unique stuff for a database. – N.B. May 13 '15 at 16:31

4 Answers4

1

You have to keep track of the allocated values and check for each newly generated one if it was already used.

function rand_md5($length) {
  $max = ceil($length / 32);
  $random = '';
  for ($i = 0; $i < $max; $i ++) {
    $random .= md5(microtime(true).mt_rand(10000,90000));
  }
  return substr($random, 0, $length);
}

$randoms = [];

do {
  $rnd = rand_md5($length);
} while( in_array( $rnd, $randoms ) );
$randoms[] = $rnd;
marekful
  • 14,986
  • 6
  • 37
  • 59
0

First suggestion, use a library better at generating unique tokens, i..e, uuid().

Secondly, ensure that your database column is long enough to store the string. Whilst probable you will generate collisions with your algorithm, frequently seems to imply you (or the database) are truncating the string.

John Cartwright
  • 5,109
  • 22
  • 25
0

Using openssl_random_pseudo_bytes:

function randomKey($length) {

    //Need a length divisible by two.
    $length = intval($length);
    if (!$length || $length % 2)
        return false;

    //Get random bytes & hex encode.
    $key = openssl_random_pseudo_bytes($length / 2);
    return (is_string($key) ? bin2hex($key) : false);

}
-1

I think it can help you

function rand_md5($length) {
  $random = md5(microtime(true).mt_rand(10000,90000));
  $random = str_shuffle($random);
  return substr($random, 0, $length);
}
user3419778
  • 856
  • 3
  • 8
  • 11