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;

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM