代码之家  ›  专栏  ›  技术社区  ›  Stunked

从列表中删除密钥

  •  0
  • Stunked  · 技术社区  · 8 年前

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

    文件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);
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Community Heathro    7 年前

    @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);
    

    Example/Demo