I have a txt file which contains domains and ips looks like this
aaa.bbb.com 8.8.8.8
bbb.com 2.2.2.2
...
...
..
How do I replace bbb.com to 3.3.3.3 but do not change aaa.bbb.com?
Here is part of my function, but not working at all.
First part I search for the match domain by reading it line by line from file
after I got the matched record ,delete it.
Second part I write a new line into it.
$filename = "record.txt";
$lines = file($filename);
foreach($lines as $line)
if(!strstr($line, "bbb.com") //I think here is the problem core
$out .= $line;
$f = fopen($filename, "w");
fwrite($f, $out);
fclose($f);
$myFile = "record.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "bbb.com\n 3.3.3.3\n";
fwrite($fh, $stringData);
fclose($fh);
after I execute my code, both aaa.bbb.com and bbb.com were deleted, how can I solve this issue?I've try "parse_url" but "parse_url" only parse url with "http://" prefix instead of a domain.
Well, sorry for the misunderstanding, this should work:
<?php
$file = "record.txt";
$search = "bbb.com";
$replace = "3.3.3.3";
$open = file_get_contents($file);
$lines = explode(PHP_EOL, $open);
$dump = "";
foreach($lines as $line){
$pos = strpos($line, $search);
if($pos === false){
echo "<b>$line</b>";
$dump .= $line.PHP_EOL;
}else{
if($pos !== 0){
$dump .= $line.PHP_EOL;
}else{
$dump .= $search." ".$replace.PHP_EOL;
}
}
}
$dump = substr($dump,0,-1);
file_put_contents($file, $dump);
?>
The easiest solution I can think of is to use substr($line,0,7) == 'bbb.com' instead of your strstr comparison.
Related
I'm writing a PHP script to search for a few lines in a pcap file. This pcap file will be piped through tail -> PHP.
I need to find a few lines like (Host: www.google.com) or (Domain: amazon.com) etc..
I'm new with PHP and struggling to get this code working, the actual output of all the fetched data need to be inserted into a SQL DB. I've used regex to filter out the binary stuff from the pcap.
I've tried multiple loops like the wile, foreach, for, but I'm not getting the clue how to do this in my script.
The code that I have so far is:
<?php
$handle = fopen('php://stdin', 'r');
$line = fgets ($handle, 1000);
$search1 = 'Location';
$search2 = 'Host:';
$search3 = 'User';
$search4 = 'Cookie';
$search5 = 'Domain:';
$matches = array();
$regex = '/[^a-zA-Z0-9\s\D\#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/';
if ($handle){
while ($handle) {
$buffer = fgets($handle);
if(strpos($buffer, $search1) !== FALSE) {
$res = preg_replace($regex, "", $buffer);
$matches[] = $res;
print_r($res). "\n";
}
}
fclose($handle);
}
?>
I've read many posts on the internet, but couldn't find any solution or I've not enough knowledge about PHP to get this done. Can anyone help me with this?
If it's working for first then loop it think about algorithm always
$handle = fopen('php://stdin', 'r');
$line = fgets ($handle, 1000);
$search = ['Location','Host:','User','Cookie','Domain:'];
$matches = array();
$regex = '/[^a-zA-Z0-9\s\D\#$%^&*()+=\-\[\]\';,.\/{}|":<>?~\\\\]/';
if ($handle){
while ($handle) {
$buffer = fgets($handle);
foreach($search as $seek){
if(strpos($buffer, $seek) !== FALSE) {
$res = preg_replace($regex, "", $buffer);
$matches[] = $res;
print_r($res). "\n";
}
}
}
fclose($handle);
}
?>
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);
I am currently trying to replace a line in a configuration file to update a version. The line looks like requiredBuild = 123456; and I need to change the numbering. I have got the following which inserts the new line after it, but I need to actually replace the existing line instead.
How would this be accomplished? ftell() is giving me the POS after the line I want to replace but removing the original line is where I am confused. Is there some way to just do like the ftell() - strlen(thisline) and replace it with ''?
<?
$config = 'serverDZ.cfg';
$file=fopen($config,"r+") or exit("Unable to open file!");
$insertPos=0;
while (!feof($file))
{
$line=fgets($file);
if (strpos($line, 'requiredBuild') !== false)
{
$insertPos = ftell($file);
$newline = "requiredBuild = 124971;\n";
break;
}
}
fseek($file, $insertPos);
fwrite($file, $newline);
fclose($file);
?>
Try this solution:
<?php
$content = file($path);
foreach ($content as $line_num => $line) {
if (false === (strpos($line, 'requiredBuild'))) continue;
$content[$line_num] = "requiredBuild = 124971;\n";
}
file_put_contents($path, implode($content));
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;
}
I have file to edit that contains:
Categories,
Diamond,10,11,
Coal,21,21,
How to add string at the end of line containing "Diamond"?
What I have is code that can add string at the end of a file but don't know how to make it to add that string in specyfic line:
$function_Result = mysql_fetch_row($function_Ask, 0);
$file_To_Edit = "item_Data.csv";
$opened_File = fopen($file_To_Edit, 'w') or die("Error. Code:2 - Can not open file $file_To_Edit");
$string_Data = $function_Result[0] . ",";
fwrite($opened_File, $string_Data);
fclose($opened_File);
I should have used an preg_replace if the file content isn't too large.
$content = file_get_contents('file.txt');
/* in case of unwanted \r */ $content = str_replace("\r", '', $content);
$content = preg_replace("#^(Diamond.*)$#m", '$1' . $append, $content);
file_put_contents('file.txt', $content);
all the previous posted solutions may fail when working on big files. here is one which works on files of any size. (should add some checks if files are readable and writeable etc.)
<?php
$file = "item_Data.csv"
$tmpFile = $file .".tmp";
$in = fopen($file, "r")
$out = fopen($tmpFile, "w")
while (($buffer = fgets($in)) !== false) {
if (preg_match('/my search pattern/', $buffer )) {
$buffer .= 'append this to the matched line';
}
fwrite($out, $buffer);
}
fclose($in);
fclose($out);
unlink($file);
rename($tmpFile, $file);
?>
<?php
$string_Data = '444555';
$file_To_Edit = "./11.csv";
$opened_File = file($file_To_Edit) or die("Error. Code:2 - Can not open file $file_To_Edit"); // Reads entire file into array of file lines
$diamond_lines = preg_grep('#^Diamond#', $opened_File); // Finds array with line started with 'Diamonds'
foreach(array_keys($diamond_lines) as $key) { // Runs 'Diamonds' array
$opened_File[$key] = substr($opened_File[$key], 0, -1) . $string_Data; // Removes the last character from 'Diamond' line (new line chracter) and adds $string_Data variable at the end
}
//var_dump($opened_File);
$f = fopen($file_To_Edit, 'w');
fwrite($f, implode("\n", $opened_File)); // Writes new .CSV file
fclose($f);
?>