Jump to content

Writing to file


hazz995

Recommended Posts

rewind($fh);

fwrite($fh, "$new_contents");

I've got it to write at the start of the file thanks to rewind but still one problem, if I open the file with r+ it overwrites existing data as it goes along instead of just nicely writing text at the start of the file without deleting anything.

 

Start:

existing text

 

Run code: (inserting the text "hello" at the start)

helloing text

 

What I'm trying to achieve:

helloexisting text

 

I tried changing the r+ to w but that just wipes everything when writing.

$string = "test text";
$fp = fopen("test.php", 'r+');
rewind($fp);
fwrite($fp, $string);
fclose($fp);

Link to comment
https://forums.phpfreaks.com/topic/190494-writing-to-file/#findComment-1004830
Share on other sites

rewind() resets the pointer to the beginning of the file. To write a new line you need to add the \n at the end of the line, else it overwrite the bytes.

 

To do what you want you need to read the file into a string then just concatenate it to your new string and rewrite it to file.

 

<?php

$string = "test";

$file = file_get_contents("./links.txt");

$string .= "$file";

file_put_contents("./links.txt", "$string");

?>

 

 

HTH

Teamatomic

Link to comment
https://forums.phpfreaks.com/topic/190494-writing-to-file/#findComment-1004836
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.