How to loop through each line in a file PHP - php

I am making a redeem key page for educational purposes with PHP just to see what it is capable of. I am storing the keys in a txt file as such:
key1
key2
And so on.
I have tried the following to loop through the txt file, insert the values into and array and work off of there. Here is what I have:
$gkey = $_GET["key"];
$file = fopen("./generatedkeys.txt", "a");
$generatedk = array();
// generate table from data in txt file
while(! feof($file)) {
$generatedk[] = fgets($file);
}
foreach ($generatedk as $key){
if ($key == hash("sha256", $gkey)){
// Removing of key from data in txt file
$contents = file_get_contents($file);
$contents = str_replace($key, '', $contents);
file_put_contents($file, $contents);
fclose($file);
$accfile = fopen("./accs.txt", "a");
fwrite($accfile, hash("sha256", $key).",".hash("sha256", $hwid)."\n");
break;
}
}
The code above however doesn't seem to be working. The key is simply not detected and not removed from generatedkeys.txt. (Not sure if there is any errors since I cannot see any).
Is there any obvious mistakes?
Any help is appreciated. Thank you.

I think this should make the process simpler, using file to read the whole file in one go into an array and then using array_search() to find if the key exists (it returns false if not found, so !== false).
Then if found, it just appends the used key to the other file, unsets the array entry for the key and overwrites the original file...
$gkey = $_GET["key"];
$generatedk = file("./generatedkeys.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ( ($entry = array_search(hash("sha256", $gkey), $generatedk)) !== false ) {
// Add key used, with whatever content you want
file_put_contents("./accs.txt", $gkey.PHP_EOL, FILE_APPEND);
// Remove found key from list in input file
unset($generatedk[$entry]);
// Overwrite input file with adjusted array
file_put_contents("./generatedkeys.txt", implode(PHP_EOL, $generatedk));
}

Your code will make some empty lines when erases key from file.
And you passed return value of fopen() as a parameter of file_get_contents(). the return value is resource on file, but file_get_contents() needs string(file path).
You can check following.
$gkey = $_GET["key"];
$file_path="./generatedkeys.txt";
$file = fopen($file_path, "a");
$generatedk = array();
// generate table from data in txt file
while(! feof($file)) {
$generatedk[] = fgets($file);
}
fclose($file);
for($i=0; $i<count($generatedk); $i++){
$key=$generatedk[$i];
if ($key == hash("sha256", $gkey)){
// Removing of key from data in txt file
array_splice($generatedk, $i, 1);
file_put_contents($file_path, implode("\n", $generatedk));
$accfile = fopen("./accs.txt", "a");
fwrite($accfile, hash("sha256", $key).",".hash("sha256", $hwid)."\n");
fclose($accfile);
break;
}
}
I hope it will be working well.
Thanks.

Related

How can I edit the content of a ini file?

I would like to be able to edit a config file for a server application using php. The config file is as follows:
include=sc_serv_public.conf
streamid_2=2
streampath_2=/relay
streamrelayurl_2=http://<full_url_of_relay_including_port>
;allowrelay=0
;allowpublicrelay=0
I would like to edit the line:
streamrelayurl_2=http://<full_url_of_relay_including_port>
and then save the file.
I am currently using:
$data = file_get_contents("sc_serv.conf"); //read the file
$convert = explode("\n", $data); //create array separate by new line
to open the file, but now I dont know how to edit it.
As an alternative, you could just use file() instead. This just loads it up into array form, no need to explode. Then after that, you just loop the elements, if the desired needle is found, overwrite it, the write the file again:
$data = file('sc_serv.conf', FILE_IGNORE_NEW_LINES); // load file into an array
$find = 'streamrelayurl_2='; // needle
$new_value = 'http://www.whateverurl.com'; // new value
foreach($data as &$line) {
if(strpos($line, 'streamrelayurl_2=') !== false) { // if found
$line = $find . $new_value; // overwrite
break; // stop, no need to go further
}
}
file_put_contents('sc_serv.conf', implode("\n", $data)); // compound into string again and write
You can use file() to read the file content to an array, then you can iterate trough the array with foreach() searching with the strstr() function the line that have your URL (in this case is in the var $id_change) and change the value. Then as you found what you needed, you end the foreach() with break. And make your string to save in the file with implode() and save the string to the config file with file_put_content().
See the code:
<?php
$new_url = 'http://www.google.com';
$id_change = 'streamrelayurl_2';
$file = "sc_serv.conf";
$data = file($file); //read the file
foreach($data as $key => $value) {
if(strstr($value, $id_change)) {
$info = $id_change . '=' . $new_url . "\n";
$data[$key] = $info;
break;
}
}
$data = implode("", $data);
file_put_contents($file, $data);
?>
Output:
include=sc_serv_public.conf
streamid_2=2
streampath_2=/relay
streamrelayurl_2=http://www.google.com
;allowrelay=0
;allowpublicrelay=0

fgetcsv skip blank lines in file

I have this script that I did, it basically grabs all the files in my "logs" folder and merge them all in one array file, my only problem is that, sometimes the script breaks if there is blank line or empty line! how can I tell it to automatically skip blank empty lines and go to next? blank lines are not necessarily at the top or bottom! could be in the middle of the csv file
<?php
$csv = array();
$files = glob('../logs/*.*');
$out = fopen("newfile.txt", "w");
foreach($files as $file){
$in = fopen($file, "r");
while (($result = fgetcsv($in)) !== false)
{
$csv[] = $result;
}
fclose($in);
fclose($out);
}
print json_encode(array('aaData' => $csv ));
?>
As you can read in the documentation for fgetcsv():
A blank line in a CSV file will be returned as an array comprising a single null field, and will not be treated as an error.
Checking for that before adding it to your data array should be sufficient:
while (($result = fgetcsv($in)) !== false) {
if (array(null) !== $result) { // ignore blank lines
$csv[] = $result;
}
}
This works 100% tested, simplest way. The explanation is that blank lines make fgetcsv return a non-empty array with just a null element inside.
if ($result[0] == NULL)
continue;
In short
$csv = array_map('str_getcsv', file($file_path, FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES));
Explanation
file reads the content of the file into an array. The FILE_SKIP_EMPTY_LINES will skip the empty lines in the file.
array_map will apply the function str_getcsv on each element of the array. str_getcsv will parse the string input for fields in
csv format and return an array containing the fields.
Read more about str_getcsv
Read more about file
Read more about array_map

How do I read each line from a file in php?

I'm new to learning php and in one of my first programs I wanted to make a basic php website with login capabilities with and array of the user and passwd.
my idea is to store the username as a list parameter and have the passwd as the contents, like this:
arr = array(username => passwd, user => passwd);
now my problem is that I don't know how I can read from the file (data.txt) so I can add it into the array.
data.txt sample:
username passwd
anotherUSer passwd
I've opened the file with fopen and stored it in $data.
You can use the file() function.
foreach(file("data.txt") as $line) {
// do stuff here
}
Modify this PHP example (taken from the official PHP site... always check first!):
$handle = #fopen("/path/to/yourfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
to:
$lines = array();
$handle = #fopen("/path/to/yourfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
lines[] = $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
// add code to loop through $lines array and do the math...
Be aware that you should not store login details in a textfile that in addition is not encrypted, this approach has severe security issues.
I know you are new from PHP, but the best approach is to store it in a DB and crypting the passwords with an algorithm such as MD5 or SHA1,
You shouldn't store sensitive information as plaintext, but to answer your question,
$txt_file = file_get_contents('data.txt'); //Get the file
$rows = explode("\n", $txt_file); //Split the file by each line
foreach ($rows as $row) {
$users = explode(" ", $row); //Split the line by a space, which is the seperator between username and password
$username = $users[0];
$password = $users[1];
}
Take a look at this thread.
This works for extremely large files as well:
$handle = #fopen("data.txt", "r");
if ($handle) {
while (!feof($handle)) {
    $line = stream_get_line($handle, 1000000, "\n");
//Do Stuff Here.
}
fclose($handle);
}
Use file() or file_get_contents() to create either an array or a string.
process the file contents as needed
// Put everything in the file in an array
$aArray = file('file.txt', FILE_IGNORE_NEW_LINES);
// Iterate throug the array
foreach ($aArray as $sLine) {
// split username an password
$aData = explode(" ", $sLine);
// Do something with the username and password
$sName = $aData[0];
$sPass = $aData[1];
}

php writing additional lines to encrypted files?

I'm trying to open an encrypted file that will store a list of information, then add a new ID with information, and save the file back as it was originally encrypted. I have xor/base64 functions that are working, but I am having trouble getting the file to retain old information.
here is what I am currently using:
$key = 'some key here';
$id = $_GET['id'];
$group = $_GET['group'];
$file = "groups.log";
$fp = fopen($file, "w+");
$fs = file_get_contents($file);
$filedec = xorstr(base64_decode($fs),$key);
$info = "$id: $group";
$filedec = $filedec . "$info\n";
$reencode = base64_encode(xorstr($filedec,$key));
fwrite($fp, $reencode);
fclose($fp);
function xorstr($str, $key) {
$outText = '';
for($i=0;$i<strlen($str);)
{
for($j=0;$j<strlen($key);$j++,$i++)
{
$outText .= $str[$i] ^ $key[$j];
}
}
return $outText;
}
?>
It should save an entire list of the ID's and their corresponding groups, but for some reason it's only showing the last input :(
I wouldn't call this encryption. "cereal box decoder ring", maybe. If you want encryption, then use the mcrypt functions. At best this is obfuscation.
The problem is that you're doing fopen() before doing file_get_contents. Using mode w+ truncates the file to 0-bytes as part of the fopen() call. So by the time file_get_contents comes up, you've deleted the original file.
$fs = file_get_contents(...);
$fh = fopen(..., 'w+');
in that order will fix the problem.

How to replace one line in php?

I have test.txt file, like this,
AA=1
BB=2
CC=3
Now I wanna find "BB=" and replace it as BB=5, like this,
AA=1
BB=5
CC=3
How do I do this?
Thanks.
<?php
$file = "data.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, 1024);
// You have the data in $data, you can write replace logic
Replace Logic function
$data will store the final value
// Write back the data to the same file
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
echo "$data <br>";
}
fclose($fp);
?>
The above peace of code will give you data from the file and helps you to write the data back to the file.
Assuming that your file is structured like an INI file (i.e. key=value), you could use parse_ini_file and do something like this:
<?php
$filename = 'file.txt';
// Parse the file assuming it's structured as an INI file.
// http://php.net/manual/en/function.parse-ini-file.php
$data = parse_ini_file($filename);
// Array of values to replace.
$replace_with = array(
'BB' => 5
);
// Open the file for writing.
$fh = fopen($filename, 'w');
// Loop through the data.
foreach ( $data as $key => $value )
{
// If a value exists that should replace the current one, use it.
if ( ! empty($replace_with[$key]) )
$value = $replace_with[$key];
// Write to the file.
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
// Close the file handle.
fclose($fh);
The simplest way (if you are talking about a small file as above), would be something like:
// Read the file in as an array of lines
$fileData = file('test.txt');
$newArray = array();
foreach($fileData as $line) {
// find the line that starts with BB= and change it to BB=5
if (substr($line, 0, 3) == 'BB=')) {
$line = 'BB=5';
}
$newArray[] = $line;
}
// Overwrite test.txt
$fp = fopen('test.txt', 'w');
fwrite($fp, implode("\n",$newArray));
fclose($fp);
(something like that)
You can use Pear package for find & replace text in a file .
For more information read
http://www.codediesel.com/php/search-replace-in-files-using-php/

Categories