Coupon system random code generator

Is this enough for a random coupon code generator? Should I check and see if the code was already used when creating the new code? What are the chances that this will happen again?

$coupon_code = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, 7); 

EDIT - here is 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 } 
+4
source share
2 answers

Here there is a coupon system that not only guarantees unique codes, but is also very effective when it comes to finding them:

 // assuming MySQL table with (id, code, effect) mysql_query( "insert into `coupons` set `effect`='".$effect."'"); // "effect" will be some keyword to identify what the coupon does $id = mysql_insert_id(); $code = $id."F"; $codelen = 32; // change as needed for( $i=strlen($code); $i<$codelen; $i++) { $code .= dechex(rand(0,15)); } mysql_query( "update `coupons` set `code`='".$code."' where `id`=".$id); // now, when you are given a code to redeem, say $_POST['code'] list($code,$effect) = mysql_fetch_row( mysql_query( "select `code`, `effect` from `coupons` where `id`='".((int) $_POST['code'])."'")); if( $code != $_POST['code']) die("Code not valid"); else { // do something based on $effect } 

As you can see, it takes an identifier from AUTO_INCREMENT , adds F, and then shims with random hexadecimal characters. You can make $codelen as high as you want, but 32 should be plenty (giving about 16 ** 26 combinations even after the millionth coupon).

+2
source

It seems pretty random to me ... I would probably probably double check that the code has not been used yet when you create it with very little chance that you will get a duplicate number.

And, most likely, the chances of a repeat are a little more than 1 in 36 ^ 8, or about 1: 2,821,109,907,456.

Note that since SHA1 returns sixteen digits in a hexadecimal string, if you want them to be less likely to duplicate, you can always just increase your substrate from (0.7) to (0.29) (you may go even a little higher, but I doubt that you want this large number)

But I agree that you should have some unique coupon identifier stored in some database to make sure you don't have duplicates, and it would be a great way to find out how many coupons you created (and maybe how many got? = D)

0
source

All Articles