Read serialized file, record by record - php

I save to file data from form:
$name = $_POST['name'];
$url = $_POST['url'];
$comm = $_POST['comm'];
$data["name"]=$name;
$data["url"]=$url;
$data["comm"]=$comm;
file_put_contents("db.txt", serialize($data));
Now, I would like to read this file record by record.
$file_handle = fopen("db.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$arr = unserialize($line);
var_dump($arr);
}
fclose($file_handle);
But this code read only last record. How to read all file?

Replace file_put_contents("db.txt", serialize($data)); to
file_put_contents("db.txt", PHP_EOL .serialize($data), FILE_APPEND);
file_put_contents("db.txt", serialize($data));// will over write the file again and again. so you cant able to read all the data. FILE_APPEND helps to append the data And PHP_EOL helps to leave a line breake.

Hi i try this code for your solution:
<?php
$name = "rdn";
$url = "http://google.it";
$comm = "com";
$data["name"]=$name;
$data["url"]=$url;
$data["comm"]=$comm;
file_put_contents("db.txt", serialize($data)."\n",FILE_APPEND);
$fh = fopen('db.txt','r');
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
var_dump(unserialize($line));
}
fclose($fh);
?>
without "\n" don't work!

Related

how to delete a single line in a txt file with php [duplicate]

This question already has answers here:
How to delete a line from the file with php?
(10 answers)
Closed last year.
i was wondering if it is posible to delete a single line in a txt file with php.
I am storing emailadresses in a flat txt file named databse-email.txt
I use this code for it:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = $_POST['email-subscribe'] . ',' . "\n";
$store = file_put_contents('database-email.txt', $email, FILE_APPEND | LOCK_EX);
if($store === false) {
die('There was an error writing to this file');
}
else {
echo "$email successfully added!";
}
}
?>
Form:
<form action="" method="POST">
<input name="email-subscribe" type="text" />
<input type="submit" name="submit" value="Subscribe">
</form>
The content of the file looks like this:
janny#live.nl,
francis#live.nl,
harry#hotmail.com,
olga#live.nl,
annelore#mail.ru,
igor#gmx.de,
natasha#hotmail.com,
janny.verlinden#gmail.com,
All lines are , seperated
Lets say i want to delete only the emailadres: igor#gmx.de
How can i do that?
What i want to achieve is a unsubscribe form and delete a single line in the .txt file
You can use str_replace
$content = file_get_contents('database-email.txt');
$content = str_replace('igor#gmx.de,', '', $content);
file_put_contents('database-email.txt', $content);
Because of the way the filesystem works you can't do this in an intuitive way. You have to overwrite the file with all the lines except the one you want to delete, here's an example:
$emailToRemove = "igor#gmx.de";
$contents = file('database-email.txt'); //Read all lines
$contents = array_filter($contents, function ($email) use ($emailToRemove) {
return trim($email, " \n\r,") != $emailToRemove;
}); // Filter out the matching email
file_put_contents('database-email.txt', implode("\n", $contents)); // Write back
Here's a streaming alternative solution in the cases where the file does not fit in memory:
$emailToRemove = "igor#gmx.de";
$fh = fopen('database-email.txt', "r"); //Current file
$fout = fopen('database-email.txt.new', "w"); //New temporary file
while (($line = fgets($fh)) !== null) {
if (trim($line," \n\r,") != $emailToRemove) {
fwrite($fout, $line, strlen($line)); //Write to new file if needed
}
}
fclose($fh);
fclose($fout);
unlink('database-email.txt'); //Delete old file
rename('database-email.txt.new', 'database-email.txt'); //New file is old file
There is also a way to do this in-place to minimize extra disk needed but that is trickier.
You can do it programmatically which will just look over every line and if it not what you want to delete, it gets pushed to an array that will get written back to the file . Like below
$DELETE = "igor#gmx.de";
$data = file("database-email.txt");
$out = array();
foreach($data as $line) {
if(trim($line) != $DELETE) {
$out[] = $line;
}
}
$fp = fopen("database-email.txt", "w+");
flock($fp, LOCK_EX);
foreach($out as $line) {
fwrite($fp, $line);
}
flock($fp, LOCK_UN);
fclose($fp);
first read the file using fopen and fget , and make array to list the emails you want to remove , use in_array to check if value exists in array , and then after remove unwanted emails save the file using fwrite and you need to close the file after the read and the write operations using fclose
checkout this code
$data = "";
$emailsToRemove = ["igor#gmx.de" , "janny#live.nl"];
//open to read
$f = fopen('databse-email.txt','r');
while ($line = fgets($f)) {
$emailWithComma = $line . ",";
//check if email marked to remove
if(in_array($emailWithComma , $emailsToRemove))
continue;
$data = $data . $line;
}
fclose($f);
//open to write
$f = fopen('databse-email.txt','w');
fwrite($f, $data);
fclose($fh);
for delete special word and next delete blank line try this:
$file = "file_name.txt";
$search_for = "example_for_remove";
$file_data = file_get_contents($file);
$pattern = "/$search_for/mi";
$file_data_after_remove_word = preg_replace($pattern, '', $file_data);
$file_data_after_remove_blank_line = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $file_data_after_remove_word);
file_put_contents($file,$file_data_after_remove_blank_line);

php set lines in a text file to an array value

Im looking to do something like the following
$file = ('file.txt');
$fopen($file);
then read each line from the file individually and set it as a specific array
like so
read $file get $line1 set as $array[0]
read $file get $line2 set as $array[1]
read $file get $line3 set as $array[2]
I would like to use these arrays created from the lines on the text file IN PLAIN TEXT like this:
$urlout = file_get_contents("http://myurl.com/?=$line1");
echo $urlout;
$urlout2 = file_get_contents("http://myurl.com/?=$line2");
echo $urlout2;
$urlout3 = file_get_contents("http://myurl.com/?=$line3");
echo $urlout3;
So if the array were 123.22.11.22 the link would look like this:
$line1 = array[0] (123.22.11.22)
$urlout = file_get_contents("http://myurl.com/?=$line1");
echo $urlout;
and the result would be
Info for 123.22.11.22
more info
some more
Modified answer as per the change indicated by the user :
Reading 2 lines on each loop..
$lines = file("file.txt");
for($i=0 ; $i<count($lines); $i=($i+2) )
{
echo file_get_contents("http://myurl.com/?=".$lines[$i]);
echo file_get_contents("http://myurl.com/?=".$lines[($i + 1)]);
}
Imp Note : A URL can be used as a filename with file_get_contents() function, only if the fopen wrappers have been enabled.
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo file_get_contents("http://myurl.com/?=$line");
}
fclose($handle);
}
The answer was to insert a "\n" separator upon inserting into the text file, then removing it after the first result was called
$lines = file("geo.txt");
for($i=0 ; $i<count($lines); $i=($i+2) )
{
echo file_get_contents("https://test.com/api/GEO.php?info=".$lines[$i]);
$lolz = file_get_contents("https://test.com/api/GEO.php?info=".$lines[($i + 1)]);
$lolz = str_replace(" \n", '', $lolz);
echo "<br>".$lolz;
}

TXT file search and delete

A (simple) question.
I have a TXT file search script in PHP.
$search = $_GET["search"];
$logfile = $_GET['logfile'];
// Read from file
$file = fopen($logfile, "r");
?> <head> <title>Searching: <?php echo $search ?></title> </head> <?php
while( ($line = fgets($file) )!= false)
{
if(stristr($line,$search)) // case insensitive
echo "<font face='Arial'> $line </font><hr>";
}
fclose($file);
Now what I want to do is delete all the text it finds in the TXT file.
I tried doing a str_replace but it didn't work.
Thanks for helping!
I think this will do the magic:
$file->ftruncate($file->ftell());
You need to gather the lines which doesn't contain the search term and you need to save the text in an array.
When you're done with the listing, you need to open the file in write mode (which will empty the file) and then write the text you gathered in the file.
Here's the code:
<?php
$search = isset($_GET["search"]) ? $_GET["search"] : '';
$logfile = isset($_GET['logfile']) ? $_GET['logfile'] : '';
$text_without_term_arr = array();
if(!empty($logfile) && !empty($search)){
// Read from file
$file = fopen($logfile, "r");
echo ' <head>
<title>Searching: ' . $search . '</title>
</head>';
while(($line = fgets($file))!== false){
if(stristr($line, $search)){
// Case insensitive search
echo '<font face="Arial">' . $line . '</font><hr/>';
} else {
// Search term not found in these lines
array_push($text_without_term_arr, $line);
}
}
fclose($file);
// Empty the file and write the text again without the search term
if(!empty($text_without_term_arr)){
$new_file = fopen($logfile, "w");
$content = implode("\n", $text_without_term_arr);
fwrite($new_file, $content);
fclose($new_file);
}
}
?>
You need another file handle to write the result out to:
$tempname=tmpname('/tmp','result');
$outfile=fopen($tempname,'w');
Next, use str_ireplace to remove the found text in each line:
$newline=str_ireplace($search, '', $line);
Then write the new line out to the out file:
fputs($outfile,$newline); // May need to send PHP_EOL too
Close the file off:
fclose($outfile);
And then rename the new file to the old filename:
rename($tempname,$logfile);

How can I add multiple strings to one text file, and read the all?

I am trying to make a program where I can add things to a list, read things, and clear the list. I have the clear function working perfectly, however I can't seem to add or read more than 1 line at a time. I am using fwrite($handle, $MyString); but that replaces everything in the entire file with $MyString. To get the information from the file I am using $list = fgets($handle); and then using echo to print it. This reads the first line in the file only.
Any help?
Thanks!
Getlist code:
<?php
$myFile = "needlist.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
Add to the list code:
<?php
$neededlist = "needlist.txt";
$fh = fopen($neededlist, 'w');
$user_message = $_REQUEST['txtweb-message'];
$needed .= $user_message;
$needed .= "\n";
fwrite($fh, $needed);
fclose($fh);
echo "You have successfully added ", $user_message;
?>
When you write to the file are you opening your filehandle with the "a" mode option? Opening with "w" or "x" truncates it so you start with a clean file (http://php.net/fopen)
fgets(); reads only until the end of the line ( http://php.net/fgets ). To get the whole file you can try:
var $list = "";
var $line = "";
while ($line = fgets($handle)) {
$list = $list . "\n" . $line;
}
echo $list;
You want to add the "\n" because fread doesn't read the linefeeds IIRC. There're also a couple functions that might be more appropriate in this situation like file_get_contents and fread.
Fgets returns only one string. You should use it in cycle like that:
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}

file_put_contents() not over writing, just appending

I have a simple file.txt which needs to be over written every time I run a certain php code.
$msg ="string";
$file = 'file.txt';
$opn = file_get_contents($file);
$opn .= $msg;
file_put_contents($file, $opn);
The code works perfectly, It added the string I want it to add, but It is appending it to the former. I want it to erase it blank and then write.
I've read the manual http://php.net/manual/en/function.file-put-contents.php
I am not using the FILE_APPEND argument either.
It's a simple thing that I'm not seeing. Help me out.
EDIT:
Here is the whole code. I'm getting some data from a site. The data is in this format 12.222 AAA and I am trying to save that to a text file to easily access later.
But for some reason something does not work. The scraper works perfectly, and the file_put_contents() woks perfectly if I set the $item="string"; but it does not work when when $item is set to equal the code below. If I echo $item I get what I want.
<?php
include('simple_html_dom.php');
$html = file_get_html('http://site.com/boom');
// find the thing in the span
foreach($html->find('div') as $article) {
$item = $article->find('span', 0)->plaintext;
echo $item;
$file = 'file.txt';
$fh = fopen( 'file.txt', 'w' );
fclose($fh);
$opn = file_get_contents($file);
$opn .= $item;
file_put_contents($file, $opn);
}
?>
you are concatenating the string in $opn .= $msg;
You can use
$msg ="string";
$file = 'file.txt';
file_put_contents($file, $msg);
No need to read the data.
You're reading the contents of the file into a string variable ($opn), appending your message ($msg) to $opn, then writing $opn back to file.... the append you're doing is
$opn .= $msg;
If you want to write only $msg to the file, then use
file_put_contents($file, $msg);
<?php
$msg ="string";
$file = 'file.txt';
$fh = fopen( 'file.txt', 'w' );
fclose($fh);
$opn = file_get_contents($file);
$opn .= $msg;
file_put_contents($file, $opn);
?>
This code will do what you are looking for..:)
file_put_contents($file, $opn,FILE_APPEND);

Categories