Stunked Stunked - 1 year ago 93
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:


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);
$rfile = fopen($file, 'w');
fwrite($rfile, $str);

Answer Source

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
// implode the keys again
$keys = implode(", ",$list);
// and save it to the file
file_put_contents('your_keys.txt', $keys);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download