php - Generating unique 6 digit code -
i'm generating 6 digit code following characters. these used stamp on stickers.
generated in batches of 10k or less (before printing) , don't envisage there ever more 1-2 million total (probably less).
after generate batches of codes, i'll check mysql database of existing codes ensure there no duplicates.
// exclude problem chars: b8g6i1l0oqds5z2 $characters = 'acefhjkmnprtuvwxy4937'; $string = ''; ($i = 0; $i < 6; $i++) { $string .= $characters[rand(0, strlen($characters) - 1)]; } return $string;
- is solid approach generating code?
- how many possible permutations there be? (6 digit code pool of 21 characters). sorry math isn't strong point
21^6 = 85766121 possibilities.
using db , storing used values bad. if want fake randomness can use following:
reduce 19 possible numbers , make use of fact groups of order p^k p odd prime cyclic.
take group of order 7^19, using generator co-prime 7^19 (i'll pick 13^11, can choose not divisible 7).
then following works:
$previous = 0; function generator($previous) { $generator = pow(13,11); $modulus = pow(7,19); //int might small $possiblechars = "acefhjkmnprtuvwxy49"; $previous = ($previous + $generator) % $modulus; $output=''; $temp = $previous; for($i = 0; $i < 6; $i++) { $output += $possiblechars[$temp % 19]; $temp = $temp / 19; } return $output; }
it cycle through possible values , little random unless go digging. safer alternative multiplicative groups forget math :(
Comments
Post a Comment