php .txt file updating with r+ mode - php

I have been searching much in google. It shows many ways but I didn't have the particular answer I've been looking for. I want to know how to edit a particular string of a line or a whole line of a .txt file via php using r+ mode.

One way is to read whole file, replace your string and write whole new string to file again... if you are working with small files. Here is example:
<?php
$file = 'filename.txt';
$fileContent = file_get_contents($file);
$replaced = str_replace("replace me", "replace with", $fileContent);
file_put_contents($file, $replaced);
?>

Related

str_replace not working with txt file PHP

str_replace doesn't seem to be working as we expect it to.
We have a text file and we're trying to remove part of the file.
while(!feof($bodyfile)) {
$content = #fgets($bodyfile);
$content = str_replace("MARGIN","",$content);
(Obviously fopen is used to open the file as 'r')
Strangely enough, finding and replacing M works? but not margin..
UPDATE:
fgets() function reads only 1 line at the time, and by putting that line in your $content variable, you're overwriting the replacement for previous line, and doing it over and over again.
Try with this:
$content = "";
while(!feof($bodyfile)) {
$line = #fgets($bodyfile);
$content .= str_replace("MARGIN","",$line);
So, what this code does is reading the line and assigning it to the $line variable, and then adding the replaced string to your $content variable.
By adding # sign in front of your functions, you're suppressing errors which that function gives.
Try to remove # from your #fgets and see if there's any error.
Try var_dump($content) or echo $content to see if file is loaded correctly.
Remember that str_replace() is case sensitive.
you could do:
$str=implode("",file('somefile.txt'));
$fp=fopen('somefile.txt','w');
$str=str_replace('MARGIN','',$str);
//OR
//$str=str_ireplace('MARGIN','',$str); for case insensitivity
fwrite($fp,$str,strlen($str));
Just found out the file is a UTF-16 character encoding rather than UTF-8 for some obscure reason. Converted, now my method originally works!
Thanks to all for suggestions

PHP: How to use str_replace?

My server has been hit with a nasty javascript iframe virus. The Trojan injects itself in to every index.php, index.html, & login.php files. The virus looks like <script>VirusCodeCrap</script>
Is there anyway I could use PHP's str_replace function to search my server and delete the virus? Would anyone know wher I could find some examples on how to do this?
Thanks,
Albert
If you are on a Unix server, sed is the best way to find and replace text in files.
If you must use PHP, the algorithm will be:
Read a file into a variable using file_get_contents()
$file_contents = file_get_contents( $filename );
Search for the replace the offending string
$file_contents = str_replace( $the_offending_text, $the_replacement_text, $file_contents);
Write $file_contents back to the file using file_put_contents:
file_put_contents( $file_contents );
str_replace() may be insufficient if the string is not precisely the same in every case. If there are variations in the offending string, you may need to use a regular expression to locate and remove them.
I would immediately delete all files from your server and re-upload clean copies from wherever your code repository is. I would also find where the code was exploited and patch that security hole.
Going about it by editing the virus out of your files seems like the long and hard way when you should have a backup of your files ( that haven't been on a live server ).

PHP appending to file from specific position

In php i am opening a text file and appending to it. However I need to append 3 chars before the end of file.
In other words i need to append/write from a specific place in the file.
Can any one help?
Best Regards
Luben
You need to open the file for edit, seek to the desired position and then write to the file, eg.:
<?php
$file = fopen($filename, "c");
fseek($file, -3, SEEK_END);
fwrite($file, "whatever you want to write");
fclose($file);
?>
Further reference at php.net - fseek doc
Hope that helps.
If it's a short text file and you are only doing this once you can read in the contents (with fread()), store it only upto 3 chars from the end using substring and then append your new content onto the end of that and write.
But as I say if this is a regular thing and/or with large files, this isn't the best approach. I'll have a think.
Hope this helps

php replace a pattern

Suppose in a file there is a pattern as
sumthing.c: and
asdfg.c: and many more.. with *.c: pattern
How to replace this with the text yourinput and save the file using php
The pattern is *.c
thanks..
You can read the contents of the file into a PHP string using file_get_contents, do the *.c to yourinput replacement in the string and write it back to the file using file_put_contents:
$filename = '...'; // name of your input file.
$file = file_get_contents($filename) or die();
$replacement = '...'; // the yourinput thing you mention in the quesion
$file = preg_replace('/\b\w+\.c:/',$replacement,$file);
file_put_contents($file,$filename) or die();
You can use PHP's str_replace or str_replace ( in case its a regex pattern). CHeck the syntax of these two functions and replace the *.c with your input.
.c pattern should be something like /?(.c)$/
First open file and get it's content:
$content = file_get_contents($path_to_file);
Than modify the content:
$content = preg_replace('/.*\.c/', 'yourinput');
Finally save the result back to the file.
file_put_contents($path_to_file, $content);
Note: You may consider changing the regexp because this way it match the '.c' string and everything before it. Maybe '/[a-zA-Z]*\.c/' is what you want.

Find and replace in a file

I want to replace certain strings with another one in a text file (ex: \nH with ,H). Is there any way to that using PHP?
You could read the entire file in with file_get_contents(), perform a str_replace(), and output it back with file_put_contents().
Sample code:
<?php
$path_to_file = 'path/to/the/file';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace("\nH", ",H", $file_contents);
file_put_contents($path_to_file, $file_contents);
?>
There are several functions to read and write a file.
You can read the file’s content with file_get_contents, perform the replace with str_replace and put the modified data back with file_put_contents:
file_put_contents($file, str_replace("\nH", "H", file_get_contents($file)));
If you're on a Unix machine, you could also use sed via php's program execution functions.
Thus, you do not have to pipe all of the file's content through php and can use regular expressions. Could be faster.
If you're not into reading manpages, you can find an overview on Wikipedia.
file_get_contents() then str_replace() and put back the modified string with file_put_contents() (pretty much what Josh said)

Categories