write to a txt file

A

Anonymous

Guest
probe said:
ok... im trying to get this script to work (nothing fancy)

i have form located at http://zeldago.com/simpsons/comments.html

and then it outputs to comments.php with this code
Code:
<?php
$file = "abc.txt";
$file_handle=fopen($file, "r+");
$now = date("y-m-d");
fputs($file_handle, $name."\n".$now."\n".$comment); 
fclose($file_handle);
?>

and its suppose to write to the top of the file without overwriting anything underneith... but for some reason it likes to write over top of ur last post... i dont know why. r+ and w+ do the same thing for this instance... and a+ just ads it underneith all the older posts...

basically i want the newer posts to appear first but cant get it to work... any suggestions???[/code]
Interesting how you can write file with right read-only?
r+ - read-only
w+ - write
http://www.php.net/manual/en/function.fputs.php

and once more try change
Code:
<?php
$file = "abc.txt";
$file_handle=fopen($file, "r+");
$now = date("y-m-d");
fputs($file_handle, $name."\n".$now."\n".$comment); 
fclose($file_handle);
?>
at this:
Code:
<?php
$file = "abc.txt";
$file_handle=fopen($file, "r");
$now = date("y-m-d");
fputs($file_handle, $name."\n".$now."\n".$comment); 
fclose($file_handle);
?>
 
The reason the rest of the file is being overwritten is because when you open the file and the pointer is put at the beginning, the file length is truncated to 0 (meaning it's erased). I did try modifying your code though, but for some reason I couldn't get it to write successfully, so I made up a whole new one. It's in 2 stages, one reads the file contents first, the next writes new contents.

Try this:
Code:
<?
$file = "abc.txt";
$now = date("y-m-d");
$fh = fopen($file,"r");
$old_contents = fread($fh,filesize($file));
fclose($fh);
$new_contents = $name."\n".$now."\n".$comment."\n".$old_contents;
$fh = fopen($file,"w");
fwrite($fh, $new_contents);
fclose($fh);
?>
 
Back
Top