Remove key from list - php

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

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

Related

PHP file with multiple lines to array and key with value

I have files with lines in it where i want to create array with a key and value
file1 has for example:
thisisline = aline
thisisalsoaline = oke
whereiamaline = check
file2 has
thisisline = aline
thisisalsoaline = oke
whereiamaline = checker
what i am trying to create but no luck to have a result which is :(
thisisline => aline
thisisalsoaline => oke
whereiamaline => check
i tried with explode but then it was like
[0] => thisisline = aline
the endgoal is to have 2 files to compare with array_diff_key so that i can identify the line whereiamaline = checker
Could somebody point me to the correct direction?
Thank you
Your files look like ini-files. php already has parse_ini_file function, which will return key => value array.
Next, correct function is array_diff_assoc:
$a = parse_ini_file('file1');
$b = parse_ini_string('file2');
print_r(array_diff_assoc($a, $b));
Because array_diff_key returns keys which are in first array, but not in second, which is not your case.
You can do it with explode function with delimeter =, like:
$finall_array = array();
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$le = explode("=",$line);
$finall_array[$le[0]] = $le[1];
}
fclose($handle);
} else {
// here goes error file opeping
}
Then just use $final_array like your output
You can do it this way.
foreach(file("file1.txt") as $line) {
$pieces = explode("=", $line);
//Do whatever you want to do with $pieces here. $pieces[0] and $pieces[1]
//Trim the values of $pieces too.
}
Another way is:
for each(file("file1.txt") as $line) {
$res[] = array_map('trim', explode('=', $line));
}
This one will directly populate the $res[] array with arrays of each line (which are trimmed)
So i used the parse_in_file together with the arra_diff_assoc and then it is
<?php
$file1 = parse_ini_file("master_manager.txt");
$file2 = parse_ini_file("master_manager1.txt");
echo "<pre>";
$myarray = array_diff_assoc($file1, $file2);
foreach ($myarray as $key => $value){
echo $key." = ".$value."\n"; }
echo "</pre>";
but then if a line contains false or true it gives a 1 or nothing (null) how to prevent that? –

Convert data to associated array php

Is it possible in php to convert this kind of data
ABANO TERME A001
ABBADIA CERRETO A004
ABBADIA LARIANA A005
ABBADIA SAN SALVATORE A006
ABBASANTA A007
ABBATEGGIO A008
ABBIATEGRASSO A010
to an associated array where in the first column are keys and in the second column are values?
$handle = fopen(path\to\file\filename, "r");
$result_arr = array();
while(($filesop = fgets($handle)) !== false)
{
$line_arr = explode(" ", $filesop);
$value = end($line_arr);
unset($line_arr[array_search($value, $line_arr)]);
$key = implode(" ", $line_arr);
$result_arr[trim($key] = trim($value);
}
print_r($result_arr);
Store in the text file like this (separated by commas):
ABANO TERME,A001
ABBADIA CERRETO,A004
ABBADIA LARIANA,A005
ABBADIA SAN SALVATORE,A006
ABBASANTA,A007
ABBATEGGIO,A008
ABBIATEGRASSO,A010
Solution to read file:
$handle = fopen(path\to\file\filename, "r");
$result_arr = array();
while(($filesop = fgets($handle)) !== false)
{
$line_arr = explode(",", $filesop);
$value = end($line_arr);
unset($line_arr[array_search($value, $line_arr)]);
$key = implode(",", $line_arr);
$result_arr[trim($key] = trim($value);
}
print_r($result_arr);
$txt = file_get_contents('foo.txt');
$arr=array_values(array_filter(explode(' ',$txt)));
$new=[];
for($i=0; $i<count($arr)-1;$i++){
$new[$arr[$i]]=$arr[++$i];
}
print_r($new);
One solution for this particular data would be:
<?php
$data = file_get_contents('data.txt')
//use regular expressions to parse whole file at once
preg_match_all("/([^\s]+\s?[^\s]+?)\s+(.\d+)$/m", $data, $m);
//and combine results from result array ($m)
//first entry - $m[0] contains whole lines thats why I dont use it here
//second entry - $m[1] - data from first brackets is an array key
//third entry - $m[2] - is a value (both are separated by some number of spaces - \s+)
$array = array_combine($m[1], $m[2]);
print_r($array);
?>
output:
Array
(
[ABETONE] => A012
[ABRIOLA] => A013
[ACATE] => A014
[ACCADIA] => A015
)
of course, as colleagues above pointed out, this depends on where data came from, and if this particular set is representative.

PHP function to edit configuration file

I'm looking for a PHP function that I can use to edit key/value pairs in a text file.
What I want to do (PHP):
changeValue(key, bar);
and have in setings.txt:
key = foo
key2 =foo2
Change to:
key = bar
key2 = foo2
What I got so far (not working):
function changeValue($input) {
$file = file_get_contents('/path/to/settings.txt');
preg_match('/\b$input[0]\b/', $file, $matches);
$file = str_replace($matches[1], $input, $file);
file_put_contents('/path/to/settings.txt', $file);
}
How to update an ini file with php? got me started. I read many other questions but I couldn't get it working.
I would use JSON with at least the JSON_PRETTY_PRINT option to write and json_decode() to read.
// read file into an array of key => foo
$settings = json_decode(file_get_contents('/path/to/settings.txt'), true);
// write array to file as JSON
file_put_contents('/path/to/settings.txt', json_encode($settings, JSON_PRETTY_PRINT));
Which will create a file such as:
{
"key": "foo",
"key2": "bar",
"key3": 1
}
Another possibility is var_export() using a similar approach, or another simple example for what you're asking:
// read file into an array of key => foo
$string = implode('&', file('/path/to/settings.txt', FILE_IGNORE_NEW_LINES));
parse_str($string, $settings);
// write array to file as key=foo
$data = implode("\n", $settings);
file_put_contents('/path/to/settings.txt', $data);
So read in the file, change the setting $setting['key'] = 'bar'; and then write it out.
Instead of using file_get_contents use file, this reads each line in as an array.
Under you see working code. Had a little problem with write array added more breaks but not sure why.
changeValue("key", "test123");
function changeValue($key, $value)
{
//get each line as an array.
$file = file("test.txt");
//go through the array, the value is references so when it is changed the value in the array is changed.
foreach($file as &$val)
{
//check if the string line contains the current key. If it contains the key replace the value. substr takes everything before "=" so not to run if the value is the same as the key.
if(strpos(substr($val, 0, strpos($val, "=")), $key) !== false)
{
//clear the string
$val = substr($val, 0, strpos($val, "="));
//add the value
$val .= "= " . $value;
}
}
//send the changed array writeArray();
writeArray($file);
}
function writeArray($array)
{
$str = "";
foreach($array as $value)
{
$str .= $value . "\n";
}
//write the array.
file_put_contents('test.txt', $str);
}
?>

Creating a function that takes arguments and passes variables

I am creating a script that will locate a field in a text file and get the value that I need.
First used the file() function to load my txt into an array by line.
Then I use explode() to create an array for the strings on a selected line.
I assign labels to the array's to describe a $Key and a $Value.
$line = file($myFile);
$arg = 3
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
This works fine but that is a lot of code to have to do over and over again for everything I want to get out of the txt file. So I wanted to create a function that I could call with an argument that would return the value of $key and $val. And this is where I am failing:
<?php
/**
* #author Jason Moore
* #copyright 2014
*/
global $line;
$key = '';
$val = '';
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$arg = 3;
$Character_Name = 3
function get_plr_data2($arg){
global $key;
global $val;
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return;
}
get_plr_data2($Character_Name);
echo "This character's ",$key,' is ',$val;
?>
I thought that I covered the scope with setting the values in the main and then setting them a global within the function. I feel like I am close but I am just missing something.
I feel like there should be something like return $key,$val; but that doesn't work. I could return an Array but then I would end up typing just as much code to the the info out of the array.
I am missing something with the function and the function argument to. I would like to pass and argument example : get_plr_data2($Character_Name); the argument identifies the line that we are getting the data from.
Any help with this would be more than appreciated.
::Updated::
Thanks to the answers I got past passing the Array.
But my problem is depending on the arguments I put in get_plr_data2($arg) the number of values differ.
I figured that I could just set the Max of num values I could get but this doesn't work at all of course because I end up with undefined offsets instead.
$a = $cdata[0];$b = $cdata[1];$c = $cdata[2];
$d = $cdata[3];$e = $cdata[4];$f = $cdata[5];
$g = $cdata[6];$h = $cdata[7];$i = $cdata[8];
$j = $cdata[9];$k = $cdata[10];$l = $cdata[11];
return array($a,$b,$c,$d,$e,$f,$g,$h,$i,$j,$k,$l);
Now I am thinking that I can use the count function myCount = count($c); to either amend or add more values creating the offsets I need. Or a better option is if there was a way I could generate the return array(), so that it would could the number of values given for array and return all the values needed. I think that maybe I am just making this a whole lot more difficult than it is.
Thanks again for all the help and suggestions
function get_plr_data2($arg){
$myFile = "player.txt";
$line = file($myFile); //file in to an array
$c = explode(" ", $line[$arg]);
$key = strtolower($c[0]);
if (strpos($c[2], '~') !== false) {
$val = str_replace('~', '.', $c[2]);
}else{
$val = $c[2];
}
return array($key,$val);
}
Using:
list($key,$val) = get_plr_data2(SOME_ARG);
you can do this in 2 way
you can return both values in an array
function get_plr_data2($arg){
/* do what you have to do */
$output=array();
$output['key'] =$key;
$output['value']= $value;
return $output;
}
and use the array in your main function
you can use reference so that you can return multiple values
function get_plr_data2($arg,&$key,&$val){
/* do job */
}
//use the function as
$key='';
$val='';
get_plr_data2($arg,$key,$val);
what ever you do to $key in function it will affect the main functions $key
I was over thinking it. Thanks for all they help guys. this is what I finally came up with thanks to your guidance:
<?php
$ch_file = "Thor";
$ch_name = 3;
$ch_lvl = 4;
$ch_clss = 15;
list($a,$b)= get_char($ch_file,$ch_name);//
Echo $a,': ',$b; // Out Puts values from the $cdata array.
function get_char($file,$data){
$myFile = $file.".txt";
$line = file($myFile);
$cdata = preg_split('/\s+/', trim($line[$data]));
return $cdata;
}
Brand new to this community, thanks for all the patience.

How can I divide data separated by commas on different lines

I have this script that extracts a .csv file from the database that holds data for different locals that a user has logged into. The .csv files come like this:
"id_user";"id_local"
"1";""
"2";"2,3,4"
"3";""
"5";"2,5"
"10";""
"13";"2"
"14";"5"
"15";"2"
"16";"1"
"20";"2"
"21";""
As you can se, it get one register per user
But, to manipulate it properly, we need it like this:
"id_user";"id_local"
"2";"2"
"2";"3
"2";"4"
"5";"2"
"5";"5"
"13";"2"
"14";"5"
"15";"2"
"16";"1"
"20";"2"
So, I need to create a function that deletes users with no local and splits different locals of the same user in different registers. Does anyone knows how can I do it?
Here is the code I have so far but I'm not sure if I'm on the right way:
function fix_local_secundario(){
$filename = "local_secundario.csv";
$file_locais = file_get_contents($filename);
$locais = explode("\n", $file_locais);
// $pattern = "/,/";
// $replacement = "\"\n;\"";
while ($line = current($locais)) {
$line = str_getcsv($line, ';', '"','\n');
// $line = preg_replace($pattern, $replacement, $line);
var_dump($line);
echo "\n";
next($locais);
}
}
Try this and see if this works:
function fix_local_secundario(){
$filename = "local_secundario.csv";
$file_locais = file_get_contents($filename);
$locais = explode("\n", $file_locais);
while ($line = current($locais)) {
// do first split on ; character
$arr1 = explode(";", $line);
// if the part after ; is not empty for this line
if ($arr1[1]!='""'){
// split it further on , character
$arr2 = explode(",", $arr1[1]);
foreach ($arr2 as $key => $val){
if($val[0] != '"'){
$val = '"'.$val;
}
if($val[strlen($val)-1] != '"'){
$val = $val . '"';
}
echo $arr1[0] . ";" . $val . "<BR>";
}
}
next($locais);
}
}
Once this basic piece is working, you should change it to return values rather than echo values since this code is part of a function as per updates made to your question.
What about this…
$f = fopen("myfile.csv", "r");
while($row = fgetcsv($f, 0, ";")){
$locals = explode(",", $row[1]);
if (count($locals)>1){
foreach($locals as $local)
// iterate with $row[0] and $local
}elseif($row[1] != "")
// use $row[0] and $row[1]
}

Categories