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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.