Core classes
<?php
namespace app\lib;
class InviteCode
{
const KEY = 'abcdefghjkmnpqrstuvwxyz123456789';
const NUM = 32;
//Pass the user id to generate a unique invitation code
public static function enCode(int $user_id)
{
$code = ''; // invitation code
while ($user_id > 0) { // convert to base
$mod = $user_id % self::NUM; // modulo
$user_id = ($user_id - $mod) / self::NUM;
$code = self::KEY[$mod] . $code;
}
$code = str_pad($code, 4, '0', STR_PAD_LEFT); // Supplement with 0 if not enough
return $code;
}
//Invitation code to get user id
public static function deCode($code)
{
if (strrpos($code, '0') !== false)
$code = substr($code, strrpos($code, '0') + 1);
$len = strlen($code);
$code = strrev($code);
$user_id = 0;
for ($i = 0; $i < $len; $i++)
$user_id += strpos(self::KEY, $code[$i]) * pow(self::NUM, $i);
return $user_id;
}
}
Test Results
20w
data is not duplicated, and the invitation code decodes userid
is correct
Precautions
- The number
0
cannot appear inKEY
KEY
cannot have duplicate strings- The length of
KEY
is not limited, but it is best not to be too short KEY
do not addi
o
l
these letters, because it is easy to confuse users
Post comment 取消回复