我正在开发一个销售软件许可证密钥的小功能。基本上它的作用是从txt获取密钥,然后它抓取一个密钥并删除文件,重写它但没有销售的密钥。我虽然遇到了问题。任何人都可以帮我发现错误,也许可以帮我修复它吗?
file.txt内容:
KEY1, KEY2, KEY3, KEY4, KEY5
我的课程:
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);
答案 0 :(得分:1)
我支持@andrewsi's comment,但您希望如何实现这一目标的一般流程如下:
// 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);