PHP生成不重复的短邀请码函数

180it 2020-09-23 AM 1772℃ 0条

生成原理

将10进制数字转换为[0-9A-Z]的36位进制字符。为了减少输入邀请码的歧义,我们将“0”和“O”去除,变成10进制转34进制;为了增加解密难度防止被猜到,我们将字符打乱;不足4位的,用0补充。

注意:$source_string字符顺序要一样,不然无法解密

加密

//生成邀请码
function createCode ($user_id)
{
    static $source_string = 'E5FCDG3HQA4B1NPIJ2RSTUV67MWX89KLYZ';
    $num = $user_id;
    $code = '';
    while ($num > 0) {
        $mod = $num % 34;
        $num = ($num - $mod) / 34;
        $code = $source_string[$mod].$code;
    }
    if(empty($code[3])){
        $code = str_pad($code, 4, '0', STR_PAD_LEFT);
    }
    return $code;
}

解密

//解析邀请码
function deCode ($code) 
{
    static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ';
    if (strrpos($code, '0') !== false){
        $code = substr($code, strrpos($code, '0')+1);
    }
    $len = strlen($code);
    $code = strrev($code);
    $num = 0;
    for ($i=0; $i < $len; $i++){
        $num += strpos($source_string, $code[$i]) * pow(34, $i);
    }
    return $num;
}

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

PHP生成不重复的短邀请码函数