php fwrite & append to PHP function - php

I am using fopen to reach my PHP file :
$readFd = #fopen($file, 'r+');
I would like to search this file for the function call parent::process();
And if this exists I would then insert a new function call after this.
I have tried using preg_replace but it does not seem to match parent::process();
For example the result I need is this.
public function process() {
parent::process();
$this->newFunction();
}
Then to write the to the file I am using :
fwrite($readFd, $content);
I guess I must be missing something important with regex.
Hopefully someone can point me in the right direction.

I would use the php function fgets to read every in the file one by one until you reach the line you need. And then your pointer will be after that line where you can write your own line.
EDIT
I was wrong, when you write something to a file at a specific point, everything after that point is lost. So I did a little testing and came up with this:
$handle = fopen($file,"r+");
$lines = array();
while(($line = fgets($handle)) !== false) {
$lines[] = $line;
if(strpos($line, 'parent::process()')) {
$lines[] = '$this->newFunction();';
}
}
fseek($handle, 0); // reset pointer
foreach($lines as $line) {
fwrite($handle, $line);
}
fclose($handle);
I hope this solves your problem.

I came up with the solution however your code seems much shorter so I will try your solution tomorrow.
if(! $readFd = #fopen($file, "r+"))
return FALSE;
$buffer = fread($readFd, 120000);
fclose($readFd);
$onDuplicate = FALSE;
$lines = explode("\n", $buffer);
foreach($lines AS $key => $line) {
if(strpos($line, "newFunction()")) {
$onDuplicate = TRUE;
}
if(strpos($line, "parent::process()")) {
$lines[$key] = "\t\tparent::process();\n\t\t//\$this->newFunction();\n";
}
}
if(! $onDuplicate) {
$readFd = fopen($file, "w");
$buffer = implode("\n", $lines)."\n";
fwrite($readFd, $buffer);
fclose($readFd);
} else {
var_dump('changes are already applied');
}
Thanks for all your help!

Related

How to find multiple lines from file with PHP?

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

Replacing a line in a file with PHP

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

Replace a particular line in a text file using php?

I have a text file that stores lastname, first name, address, state, etc as a string with a | delimiter and each record on a separate line.
I have the part where I need to store each record on a new line and its working fine; however, now I need to be able to go back and update the name or address on a particular line and I can't get it to work.
This how to replace a particular line in a text file using php? helped me here but I am not quite there yet. This overwrites the whole file and I lose the records. Any help is appreciated!
After some edit seems to be working now. I am debugging to see if any errors.
$string= implode('|',$contact);
$reading = fopen('contacts.txt', 'r');
$writing = fopen('contacts.tmp', 'w');
$replaced = false;
while (!feof($reading)) {
$line = fgets($reading);
if(stripos($line, $lname) !== FALSE) {
if(stripos($line, $fname) !== FALSE) {
$line = "$string";
$replaced = true;
}
}
fwrite($writing, "$line");
//fputs($writing, $line);
}
fclose($reading); fclose($writing);
// might as well not overwrite the file if we didn't replace anything
if ($replaced)
{
rename('contacts.tmp', 'contacts.txt');
} else {
unlink('contacts.tmp');
}
It seems that you have a file in csv-format. PHP can handle this with fgetcsv() http://php.net/manual/de/function.fgetcsv.php
if (($handle = fopen("contacts.txt", "r")) !== FALSE) {
$data = fgetcsv($handle, 1000, '|')
/* manipulate $data array here */
}
fclose($handle);
So you get an array that you can manipulate. After this you can save the file with fputcsv http://www.php.net/manual/de/function.fputcsv.php
$fp = fopen('contacts.tmp', 'w');
foreach ($data as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Well, after the comment by Asad, there is another simple answer. Just open the file in Append-mode http://de3.php.net/manual/en/function.fopen.php :
$writing = fopen('contacts.tmp', 'a');

Read and iterate .txt in PHP

I sense that I am almost there.
Here is a .txt file, which is about 60 Kbytes and full of German words. Every word is on a new line.
I want to iterate through it with this code:
<?php
$file = "GermanWords.txt";
$f = fopen($file,"r");
$parts = explode("\n", $f);
foreach ($parts as &$v)
{
echo $v;
}
?>
When I execute this code, I get: Resourceid#2
The word resource is not in the .txt, I do not know where it comes from.
How can I manage to show up all words in the txt?
No need for fopen just use file_get_contents:
$file = "GermanWords.txt";
$contents = file_get_contents($file);
$lines = explode("\n", $contents); // this is your array of words
foreach($lines as $word) {
echo $word;
}
fopen() just opens the file, it doesn't read it -- In your code, $f contains a file handle, not the file contents. This is where the word "Resource" comes from; it's PHP's internal name for the file handle.
One answer would be to replace fopen() with file_get_contents(). This opens and reads the file in one action. This would solve the problem, but if the file is big, you probably don't want to read the whole thing into memory in one go.
So I would suggest instead using SplFileObject(). The code would look like this:
<?php
$file = "GermanWords.txt";
$parts = new SplFileObject($file);
foreach ($parts as $line) {
echo $line;
}
?>
It only reads into memory one line at at time, so you don't have to worry about the size of the file.
Hope that helps.
See the PHP manual for more info: http://php.net/manual/en/splfileobject.construct.php
$f, the result of fopen is a resource, not the contents of the file. If you just want an array of the lines contained in the file, you can use file:
$parts = file('GermanWords.txt');
foreach($parts as $v){
echo $v;
}
Alternatively, if you want to stick with fopen you can use fread to read the content:
$f = fopen('GermanWords.txt', 'r');
// read the entire file into $contents
$contents = fread($f, filesize('GermanWords.txt'));
fclose($handle);
$parts = explode("\n", $contents);
The SplFileObject provides a way to do that :
$file = new SplFileObject("file.txt");
while (!$file->eof()) {
echo $file->fgets();
}
And if you prefer the foreach loop, you can create a generator function for that :
function lines($filename) {
$file = new SplFileObject($filename);
while (!$file->eof()) {
yield $file->fgets();
}
}
foreach (lines('German.txt') as $line) {
echo $line;
}
Reading the entire content of the file (with file_get_contents) before treating it can be memory consuming.
If you want to treat a file line by line, this class might help you.
It implements an Iterator (see phpdoc about it), that can be walked through in a foreach loop. Only the last line read is stored in memory.
class TxtFileIterator implements \Iterator{
protected $fileHandler;
protected $key;
protected $current;
protected $fileName;
function __construct($fileName){
$this->fileHandler = fopen($fileName, "r") or die("Unable to open file!");
$this->fileName = $fileName;
$this->key = 0;
}
function __destruct(){
fclose( $this->fileHandler );
}
//Iterator interface
public function current (){
return $this->current;
}
public function key (){
return $this->key;
}
public function next (){
if ( $this->valid() ){
$this->current = fgets( $this->fileHandler );
$this->key++;
}
}
public function rewind (){
$this->__destruct();
$this->__construct( $this->fileName );
}
public function valid (){
return !feof( $this->fileHandler );
}
Usage :
$iterator = new TxtFileIterator("German.txt");
foreach ($iterator as $line) {
echo $line;// or do whatever you want with line
}

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];
}

Categories