Comparing string with file - php

I want to add string text (ip adress) in end of file if not exist.
I have a database with IP Adress, I want to add ip if not exist in my text file.
$rows=mysql_num_rows($resultcheck);
$fields=mysql_num_fields($resultcheck);
for ($i=0;$i<$rows;$i++){
for($j=0;$j<$fields;$j++){
//echo '<b>Date : </b>'.date("Y-m-d").' IP : ';
//echo long2ip(mysql_result($resultcheck,$i,$j)).'<br>';
$file=fopen("ff.txt","a+");
fputs($file,long2ip(mysql_result($resultcheck,$i,$j)).":");
$line=file('ff.txt');
foreach($line as $line){
$arr=explode(':',$line);
if ($arr[0] != long2ip(mysql_result($resultcheck,$i,$j))){
fputs($file,long2ip(mysql_result($resultcheck,$i,$j)).":");
}
}
}
}

For add strings to end of file open file with flag "a"
For compare string - you can open file with function file. It return array of lines in file. For find similar string just use foreach by this array from file.
In other words - show your code

Read line by line from file
<?php
$handle = #fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
Append to file
<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file,
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

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

Delete last line and check data in text file

I have the following code to write data to a text file.
$somecontent = "data|data1|data2|data3";
$filename = 'test.txt';
// Let's make sure the file exists and is writable first.
IF (IS_WRITABLE($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
IF (!$handle = FOPEN($filename, 'a')) {
PRINT "Cannot open file ($filename)";
EXIT;
}
// Write $somecontent to our opened file.
IF (!FWRITE($handle, $somecontent)) {
PRINT "Cannot write to file ($filename)";
EXIT;
}
PRINT "Success, wrote ($somecontent) to file ($filename)";
FCLOSE($handle);
} ELSE {
PRINT "The file $filename is not writable";
}
Now I want this text file to only every have 10 lines of data and when a new line of data is added which is unique to the other lines then the last line of data is deleted and a new line of data is added.
From research I have found the following code however total no idea how to implement it on the above code.
check for duplicate value in text file/array with php
and also what is the easiest way to implement the following code?
<?
$inp = file('yourfile.name');
$out = fopen('yourfile.name','w');
for ($I=0;$i<count($inp)-1);$i++)
fwrite($out,$inp[$I]);
fclose($out)l
?>
Thanks for any help from a PHP newbie.
$file = fopen($filename, "r");
$names = array();
// Put the name part of each line in an array
while (!feof($file)) {
$line_data = explode("|", $fgets($file));
$names[] = $line_data[0]
}
$data_to_add = "name|image|price|link"
$data_name = "name" // I'm assuming you have this in a variable somewhere
// If the new data does not exist in the array
if(!in_array($data_name, $names)) {
unset($lines[9]); // delete the 10th line
array_unshift($lines, $data_to_add); // Put new data at the front of the array
// Write the new array to the file
file_put_contents($filename, implode("\n", $lines));
}

php reading from file and manipulating the data

I am having some difficulty with reading info from a text file. Is it possible to use php and get one line at a time, and compare that line to a variable, one character at a time? Every time I add the character searching algorithm it messes up. or does the file reading only do full files/lines/character
ex:
$file=fopen("text/dialogue.txt","r") or exit("unable to open dialogue file");
if($file == true) {
echo "File is open";
fgets($file);
$c = "";
while(!feof($file)) {
$line = fgets($file)
while($temp = fgetc($line)) {
$c = $c . $temp;
//if statement and comparrison
}
}
} else {
echo "File not open";
}
fclose($file);
You may use php file function to read a file line by line
<?php
$lines = file("myfile.txt");
foreach($lines as $line){
## do whatever you like here
echo($line);
}
?>
Please check php manual
http://php.net/manual/en/function.file.php

PhP - How to place different strings into repeating embedding text?

OK so let's say I have a .txt file with the following lines:
Mark
Jane
Ann
How could I make a php code which reads these names line by line and then saves them in a new text file like this:
Hi my name is Mark, what's yours?
Hi my name is Jane, what's yours?
hi my name is Ann, what's yours?
P.S - This is a simplified version of my problem, I actually have a list of URLs that I need to sorround by some XML code and then stack those one on top of another, so it turns out to be one big XML file. The surrounding blocks of XML text are static, they don't change, the only thing that should change is the part where the URL needs to be inserted, of course.
How about this: (result.txt contains your result, and input.txt contains your names)
<?php
$filename = "result.txt";
if (!$handleRes = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
$handle = #fopen("input.txt", "r");
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
fwrite($handleRes, "Hi my name is ".chop($buffer).", what's yours?\n");
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>
$aString = file_get_contents("text.txt"); // get text from file
$aString = explode("\n", $aString); // split this text with new line character
$aString = array_map('trim',$aString); // remove spacing between left and right
foreach($aString as $index => $strString){ // browse each line
$aString[$index] = "Hi my name is $strString, what's yours?"; // change to new format
}
$aString = implode("\r\n", $aString); // join array to string
echo $aString;
Open the file, and then read.
$names = file("names.txt");
foreach ($names as $name) {
printf("Hi My name is %s, What's yours?\n", $name);
}

Trying to insert text into a file ABOVE a certain line

I have a text file, more of a users file for a program. Im trying to use PHP to insert new data before groups: in the file. The last user is above this line and i want to insert new users below the last user and above groups: in the file
Ive been tinkering and was trying some things, but i can only get it after that line.
heres what i have
$key = 'groups:';
$newline = 'blackberry';
//copy file to prevent double entry
$file = "data2.yml";
$newfile = "filetemp.txt";
copy($file, $newfile) or exit("failed to copy $file");
//load file into $lines array
$fc = fopen ($file, "r");
while (!feof ($fc))
{
$buffer = fgets($fc, 4096);
$lines[] = $buffer;
}
fclose ($fc);
//open same file and use "w" to clear file
$f=fopen($newfile,"w") or die("couldn't open $file");
/* uncomment to debug */
print_r($lines);
print "\n";
//loop through array using foreach
foreach($lines as $line)
{
fwrite($f,$line); //place $line back in file
if (strstr($line,$key)){ //look for $key in each line
fwrite($f,$newline."\n");
} //place $line back in file
}
fclose($f);
copy($newfile, $file) or exit("failed to copy $newfile");
?>
Its a yml file, so i cant add an extra line to post after or it screws up and refuses to run.
thanks!
your foreach code should be:
foreach($lines as $line)
{
if (strstr($line,$key)){ //look for $key in each line
fwrite($f,$newline."\n"); //insert data before line with key
}
fwrite($f,$line); //place $line back in file
}
This way you will write the new data first then the original data.

Categories