PHP生成唯一固定长度邀请码

function create_invite_code() {
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0,25)]
        .strtoupper(dechex(date('m')))
        .date('d')
        .substr(time(),-5)
        .substr(microtime(),2,5)
        .sprintf('%02d',rand(0,99));
    for(
        $a = md5( $rand, true ),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        $d = '',
        $f = 0;
        $f < 6;
        $g = ord( $a[ $f ] ),
        $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
        $f++
    );
    return $d;
}

经测试,基本不重复。如果高并发会出现极个别的重复。
可以通过查询数据库是否存在来避免。

// 连接数据库
require_once ('vendor/joshcam/mysqli-database-class/MysqliDb.php');
$db = new MysqliDb (Array (
    'host' => '127.0.0.1',
    'username' => 'root',
    'password' => '123456',
    'db'=> 'test',
    'port' => 3306,
    'prefix' => '',
    'charset' => 'utf8'));

$code = create_invite_code();

$r = true;
while($r) {
    $db->where("code", $code);
    $r = $db->has("table_code");
    if ($r) {
        $code = create_invite_code();
    }
}

echo $code;

如果存在,就重新生成一个,直到不重复,再保存。

原文地址:https://www.cnblogs.com/jiqing9006/p/9076008.html