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

vern

Dominus
Political Access
Joined
2 Mar 2002
Messages
1,572
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.
 
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);
?>
 
@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 profile posts

Also Hi EP and people. I found this place again while looking through a oooollllllldddd backup. I have filled over 10TB and was looking at my collection of antiques. Any bids on the 500Mhz Win 95 fix?
Any of the SP crew still out there?
Xie wrote on Electronic Punk's profile.
Impressed you have kept this alive this long EP! So many sites have come and gone. :(

Just did some crude math and I apparently joined almost 18yrs ago, how is that possible???
hello peeps... is been some time since i last came here.
Electronic Punk wrote on Sazar's profile.
Rest in peace my friend, been trying to find you and finally did in the worst way imaginable.

Forum statistics

Threads
62,015
Messages
673,494
Members
5,621
Latest member
naeemsafi
Back