Chris
Chris

Reputation: 483

How to overwrite a particular line in flat file?

My text file contains:

a
b
c
d
e

I can't figure out how to amend my code so that I can overwrite line 3 ONLY (ie replacing "c") with whatever I type into the input box 'data'. My code is as follows, currently the contents of the input box 'data' replaces my file entirely:

$data = $_POST['data'];
$file = "data.txt"; 

$fp = fopen($file, "w") or die("Couldn't open $file for writing");

fwrite($fp, $data) or die("Couldn't write values to file"); 
fclose($fp);

I have it working the other way around, ie the code below reads line 3 ONLY into the text box when the page first loads:

$file = "data.txt";
$lines = file( $file ); 
echo stripslashes($lines[2]);

Can anybody advise the code I need to use to achieve this?

Upvotes: 1

Views: 314

Answers (1)

Tino Didriksen
Tino Didriksen

Reputation: 2255

The only way is to read the whole file, change the 3rd line, then write it all back out. Basically, like so:

$lines = file($file);
$lines[2] = $_POST['data'];
file_put_contents($file, implode("\n", $lines));

Btw, your reading code does not "ONLY" read line 3 - it reads all lines as per file() and then you only use line 3.

Upvotes: 4

Related Questions