需求:
- 生成的防伪码长度大概在 12~18 位
- 有可能是纯数字,或者字母+数字
- 绝对不能重复 某 cms 防伪系统的生成防伪码的源码;
function genRandomString($len, $t = 0) { $chars = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "2", "3", "4", "5", "6", "7", "8", "9"); $chars1 = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"); $chars2 = array("1", "2", "0", "3", "4", "5", "6", "7", "8", "9"); $chars3 = array("A", "B", "C", "D", "E", "F", "G", "O", "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"); if ($t == 1) { $charsLen = count($chars1) - 1; shuffle($chars1); $output = ""; for ($i = 0; $i < $len; $i++) { $output .= $chars1[mt_rand(0, $charsLen)]; } } else if ($t == 2) { $charsLen = count($chars2) - 1; shuffle($chars2); $output = ""; for ($i = 0; $i < $len; $i++) { $output .= $chars2[mt_rand(0, $charsLen)]; } } else if ($t == 3) { $charsLen = count($chars3) - 1; shuffle($chars3); $output = ""; for ($i = 0; $i < $len; $i++) { $output .= $chars3[mt_rand(0, $charsLen)]; } } else { $charsLen = count($chars) - 1; shuffle($chars); $output = ""; for ($i = 0; $i < $len; $i++) { $output .= $chars[mt_rand(0, $charsLen)]; } } return $output; }
基本就是金刚葫芦娃,一股脑生成,插入数据库。连判断都没有。虽然重复的概率小,但还是有可能呀。怎么做到一个优秀一点的?
- 我想的就只是插入的时候返回 0 或者 1,循环结束计算返回 1 的集合,是否等于要生成的防伪码数量,如果不等于,(这时候,数量级已经下降了很多)
- 来一个死循环,一次生成一个插入数据库,知道成功的条数弥补上一次重复的数量,跳出循环。
有没有更好的方法?

是防伪码呀 >_<