• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

[PHP] Writing to file ... starting at the beginning.

vern

Dominus
Political User
#1
The following code appends to file successfully and works perfectly.

Code:
$handle = fopen("recent.txt", 'a'); 
fwrite($handle, $add); 
fclose($handle);
However ... this code doesn't seem to write to the file. The only different is that I want this code to set the pointer at the beginning of the file instead of the end. Anybody have any clues to what is going on?

Code:
$handle = fopen("recent.txt", 'r+'); 
fwrite($handle, $add); 
fclose($handle);
If you have code that does the same thing (writes a line at the beginning of a file), but is better and/or more efficient, please post.
 
#3
are you wanting to keep the contents of the file and just stick a line at the top?

if you want to do that, you are going to need to read out the contents first and then append that to the end of the string you want at the top and then write the whole lot back again.

PHP:
<?php
$file_contents = file_get_contents("recent.txt");
$new_file = $new_first_line . "\n" . $file_contents;
$fp = @fopen("recent.txt", "w");
frwite($fp, $new_file);
fclose($fp);
?>
 

vern

Dominus
Political User
#4
@Geffy ... exactly what I was looking for! Much thanks!

I didn't realize you had to create put the whole stream into a variable and then write that. Thanks.
 

Members online

No members online now.

Latest posts

Latest profile posts

Hello, is there anybody in there? Just nod if you can hear me ...
Xie
What a long strange trip it's been. =)

Forum statistics

Threads
61,961
Messages
673,239
Members
89,014
Latest member
sanoravies