Stunked Stunked - 5 months ago 9
PHP Question

Remove key from list

i'm working on a small function for selling software license keys. Basically what it does is it gets keys from a txt, and then it grabs a key and deletes the file, rewrites it but without the key that was sold. I've got a issue though. Could anyone help me spot the error and perhaps help me fix it?

file.txt contents:

KEY1, KEY2, KEY3, KEY4, KEY5


My class:

class Key {

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

}


My function:

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

Answer

I'd side with @andrewsi's comment, but the general flow of how you want to achieve this is as such:

// 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