Is this good enough for a random coupon code generator? Should I check and see if a code has already been used when I make a new code? What are the odds that this will repeat?
$coupon_code = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 7);
EDIT – here’s my actual code:
$coupon_code = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 7);
$numrows = mysql_num_rows(mysql_query("SELECT id FROM generatedcoupons WHERE coupon_code='$coupon_code' LIMIT 1"));
if($numrows>0){
$coupon_code = substr(base_convert(sha1(uniqid(rand())), 16, 36), 0, 7);
$numrows = mysql_num_rows(mysql_query("SELECT id FROM generatedcoupons WHERE coupon_code='$coupon_code' LIMIT 1"));
if($numrows>0)
//error, show link to retry
}
Here’s a coupon system that not only guarantees unique codes, but is very efficient when it comes to looking them up:
As you can see, it takes the ID from
AUTO_INCREMENT, appends an F, then pads with random hexadecimal characters. You can make$codelenas high as you want, but 32 should be plenty (giving around 16**26 combinations even after the millionth coupon).