php file_put_content overwrite - php

So i found this code which lets be write to a specific line
function SetSiteName(){
global $session, $database, $form;
$filepathname = "include/classes/constants.php";
$target = 'sitename';
$newline = 'define("sitename", "Testing.");';
$stats = file($filepathname, FILE_IGNORE_NEW_LINES);
$offset = array_search($target,$stats) +32;
array_splice($stats, $offset, 0, $newline);
file_put_contents($filepathname, join("\n", $stats));
header("Location: ".$session->referrer);
}
however it will not overwrite whats on that line it'll go to the next line and put the data in.. I'd like to make it overwrite what currently is on that line?
Any thoughts?

You can overwrite a line of a file with this code.
$filename = "file.txt";
$content = file_get_contents($filename);
$lines_array = explode(PHP_EOL, $content);
//overwrite the line that you want.
$lines_array[5] = "New text at line 6!";
file_put_contents($filename, implode(PHP_EOL, $lines_array));

Related

PHP: Replace line in a file or add if not found

I have a file (messages.txt) that looks something like this:
112233|A line of text here.
aabbcc|More text here.
223344|And the list goes on...
and code like this that works as expected:
$filename = 'messages.txt';
$data = file($filename);
file_put_contents($filename, implode('',
array_map(function($data) {
return stristr($data,'aabbcc') ? "aabbcc|This would be a NEW line.\n" : $data;
}, file($filename))
));
So this will replace the line where it finds aabbcc with a new one.
How do I edit this so that if the line isn't found, it would add it at the end of the txt file? Is there an easy way to do this or would I need to alter the code quite a bit to make it work? Thanks.
You can do something like this:
$message_exists = false;
$filename = 'messages.txt';
$data = file($filename);
file_put_contents($filename, implode('',
array_map(function($data) use (&$message_exists){
$result = substr($data, 0, strlen('aabbcc|')) === 'aabbcc|';
if($result)
{
$message_exists = true;
}
return $result ? "aabbcc|This would be a NEW line.\n" : $data;
}, file($filename))
));
if(!$message_exists)
{
file_put_contents($filename, "aabbcc|This would be a NEW line.\n", FILE_APPEND);
}

Read serialized file, record by record

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!

Write to file using SplFileObject()

I'm trying to edit a file by line using SplFileObject(). I can choose the line of the file I want to edit. But how do I then write a $string to that line?
Here is my code to get the line:
<?php
$file = new SplFileObject('myfile.txt');
$file->seek(9999); // Seek to line no. 10,000
echo $file->current(); // Print contents of that line
?>
How do I insert a string on that line?
Note, I don't want to overwrite the file, I simply want to insert a $string at a given line.
This isn't probably the best solution as it will read the whole file and store it in a string. But since there are no other answers you can use this as your last resource.
$ouput = '';
$file = new SplFileObject("your_file.xxx", 'r');
while (!$file->eof()) {
$line = $file->fgets();
if($line == 'your_condition'){
$line = 'replace this line';
}
$output .= $line;
}
$file = null;
$file = new SplFileObject("your_file.xxx", 'w+');
$file->fwrite($output);

How to find in file line that contains string and add something at the end of that line

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

Write to specific line in PHP

I'm writing some code and I need to write a number to a specific line. Here's what I have so far:
<?php
$statsloc = getcwd() . "/stats/stats.txt";
$handle = fopen($statsloc, 'r+');
for($linei = 0; $linei < $zone; $linei++) $line = fgets($handle);
$line = trim($line);
echo $line;
$line++;
echo $line;
I don't know where to continue after this. I need to write $line to that line, while maintaining all the other lines.
you can use file to get the file as an array of lines, then change the line you need, and rewrite the whole lot back to the file.
<?php
$filename = getcwd() . "/stats/stats.txt";
$line_i_am_looking_for = 123;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$lines[$line_i_am_looking_for] = 'my modified line';
file_put_contents( $filename , implode( "\n", $lines ) );
This should work. It will get rather inefficient if the file is too large though, so it depends on your situation if this is a good answer or not.
$stats = file('/path/to/stats', FILE_IGNORE_NEW_LINES); // read file into array
$line = $stats[$offset]; // read line
array_splice($stats, $offset, 0, $newline); // insert $newline at $offset
file_put_contents('/path/to/stats', join("\n", $stats)); // write to file
I encountered this today and wanted to solve using the 2 answers posted but that didn't work. I had to change it to this:
<?php
$filepathname = "./stats.txt";
$target = "1234";
$newline = "after 1234";
$stats = file($filepathname, FILE_IGNORE_NEW_LINES);
$offset = array_search($target,$stats) +1;
array_splice($stats, $offset, 0, $newline);
file_put_contents($filepathname, join("\n", $stats));
?>
Because these lines don't work since the arg of the array is not an index:
$line = $stats[$offset];
$lines[$line_i_am_looking_for] = 'my modified line';
Had to add that +1 to have the new line under the searched text.

Categories