从列表中删除密钥

Remove key from list

我正在开发一个销售软件许可证密钥的小功能。基本上它所做的是从一个 txt 中获取密钥,然后它获取一个密钥并删除文件,重写它但没有出售的密钥。我有一个问题。谁能帮助我发现错误并帮助我修复它?

file.txt内容:

KEY1, KEY2, KEY3, KEY4, KEY5

我的class:

class Key {

 public static function getRandomKey($keyset)
 {
    $i = rand(0, count($keyset));
    return $keyset[$i];
 }

}

我的函数:

$file = 'file.txt';
$contents = file_get_contents($file);
$contents = str_replace(' ', '', $contents);
$keyset = explode(',', $contents);
$key = Key::getRandomKey($keyset);
echo $key;
$str = implode(',', $keyset);
unlink($file);
$rfile = fopen($file, 'w');
fwrite($rfile, $str);
fclose($rfile);

我会站在 一边,但是您要如何实现这一点的一般流程是这样的:

// fetch
$keys = file_get_contents('your_keys.txt');
// explode
$list = explode(",", $keys);
// get random key (this would be your Key::getRandomKey() function)
$use = rand(0, (count($list) - 1)); // notice how we do count($list) - 1? Since the index starts at 0, not 1, you need to account for that ;-)

// now get a key
echo $list[$use];
// unset that key from the list
unset($list[$use]);
// implode the keys again
$keys = implode(", ",$list);
// and save it to the file
file_put_contents('your_keys.txt', $keys);

Example/Demo