这对于随机优惠券代码生成器来说是否足够好?当我创建一个新代码时,我应该检查并查看一个代码是否已经被使用过吗?这种情况重演的几率有多大?

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

编辑 - 这是我的实际代码:
$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
}

最佳答案

这是一个优惠券系统,它不仅保证唯一的代码,而且在查找它们时非常有效:

// 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
}

如您所见,它从 AUTO_INCREMENT 获取 ID,附加一个 F,然后填充随机的十六进制字符。您可以根据需要将 $codelen 设置得尽可能高,但 32 应该足够了(即使在第 100 万张优惠券之后也能提供大约 16**26 种组合)。

关于php - 优惠券系统随机码生成器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7563416/

10-11 19:31