gpt4 book ai didi

php - 使用 PHP 生成串行

转载 作者:可可西里 更新时间:2023-11-01 13:02:03 24 4
gpt4 key购买 nike

在我作为 PHP 程序员和 C# 编程初学者的这些日子里,我一直想知道生成独特序列的最佳方法,例如 Microsoft Office 和 Microsoft 操作系统的做法。

有没有人对如何处理这个有很好的指导,比如生成唯一序列的重要因素是什么,防止重复等等。关于如何创建/验证它们的小例子。

这是我正在谈论的 RFC:https://www.rfc-editor.org/rfc/rfc1982 .

最佳答案

这是我们的解决方案。它根据有效的 IPv4、Userid(或任何有意义的整数)或文本字符串生成具有可配置大小/长度和可选后缀的 key 。它还避免了标准结果中的歧义字符 (i,1,l,0,o,O)。

我们将 Userid 附加到许可证中,稍后可以将该部分转换回 base10 整数,并检查它是否对使用该许可证的用户帐户有效。

$license = generate_license();
// YF6G2-HJQEZ-8JZKY-8C8ZN

$license = generate_license(123456);
// ZJK82N-8GA5AR-ZSPQVX-2N9C

$license = generate_license($_SERVER['REMOTE_ADDR']);
// M9H7FP-996BNB-77Y9KW-ARUP4

$license = generate_license('my text suffix');
// Q98K2F-THAZWG-HJ8R56-MY-TEXT-SUFFIX

我们确实会在创建时检查数据库中的唯一性,但是将 IP/用户 ID 与随机性结合使用,重复的可能性几乎为零。

/**
* Generate a License Key.
* Optional Suffix can be an integer or valid IPv4, either of which is converted to Base36 equivalent
* If Suffix is neither Numeric or IPv4, the string itself is appended
*
* @param string $suffix Append this to generated Key.
* @return string
*/
function generate_license($suffix = null) {
// Default tokens contain no "ambiguous" characters: 1,i,0,o
if(isset($suffix)){
// Fewer segments if appending suffix
$num_segments = 3;
$segment_chars = 6;
}else{
$num_segments = 4;
$segment_chars = 5;
}
$tokens = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
$license_string = '';
// Build Default License String
for ($i = 0; $i < $num_segments; $i++) {
$segment = '';
for ($j = 0; $j < $segment_chars; $j++) {
$segment .= $tokens[rand(0, strlen($tokens)-1)];
}
$license_string .= $segment;
if ($i < ($num_segments - 1)) {
$license_string .= '-';
}
}
// If provided, convert Suffix
if(isset($suffix)){
if(is_numeric($suffix)) { // Userid provided
$license_string .= '-'.strtoupper(base_convert($suffix,10,36));
}else{
$long = sprintf("%u\n", ip2long($suffix),true);
if($suffix === long2ip($long) ) {
$license_string .= '-'.strtoupper(base_convert($long,10,36));
}else{
$license_string .= '-'.strtoupper(str_ireplace(' ','-',$suffix));
}
}
}
return $license_string;
}

关于php - 使用 PHP 生成串行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3687878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com