Page 1 of 1
need help writing to a file
Posted: Thu Jan 30, 2003 2:11 am
by wickedest
hi, i made this simple/tiny script for people to add a comment on my site, and it shows the date added...but when you use it it prints it out old-to-new, i want the newer ones first, is this possiible?
Code: Select all
<?php
$date = date("Y-m-d");
$file_handle = fopen("comments.txt", "a");
$content = stripslashes($_POST['comments']);
$entry = "<HR color=990000 size=1><font color=ff6600>$date</font><br> $content\n";
fputs($file_handle, $entry);
fclose($file_handle);
header("Location: index.php");
?>
Posted: Thu Jan 30, 2003 2:17 am
by evilcoder
From what i know PHP will write to the end of the file, and read from top to bottom, i'm pretty sure you cant change the way it reads the file.
Posted: Thu Jan 30, 2003 2:28 am
by wickedest
i had a script(same as mine/by someone else) it printed new-to-old, but it wont work on php4.......here it is....
Code: Select all
<?php
if(strlen($note)>0)
{
$wp=fopen("guests.tmp","w");
$rp=fopen("guests.txt","r");
fputs($wp,"\n<HR color="#830E0E" size=1>".date("Y-m-d")."<BR>\n");
fputs($wp,"<font color=eecb22 size=1>".stripslashes($note)."</font>\n");
while(!feof($rp)) fputs($wp,fgets($rp,4096));
fclose($wp);
fclose($rp);
copy("guests.tmp","guests.txt");
}
header("Location: guestbook.html");
?>
Posted: Thu Jan 30, 2003 4:01 am
by lazy_yogi
you could read the whole file into a string first then write the new comment and the the string after it.
Code: Select all
$date = date("Y-m-d");
$content = stripslashes($_POST['comments']);
$entry = "<HR color=990000 size=1><font color=ff6600>$date</font><br>$content\n";
$fp = fopen("comments.txt", 'r');
$filedata = fread($fp, filesize("comments.txt"));
fclose($fp);
$filedata = $entry.$filedata
$f = fopen("comments.txt", 'w'));
fwrite($f, "$filedata");
fclose($f);
Posted: Thu Jan 30, 2003 12:57 pm
by wickedest
im sorry but that isn't writing to the file -- is it possible to show what errors happen or no?
Posted: Thu Jan 30, 2003 7:06 pm
by lazy_yogi
there were a couple of syntax errors .. I tested this and it works for me :
Code: Select all
<?php
$date = date("Y-m-d");
// $content = stripslashes($_POST['comments']);
$content = "ne this is a new line";
$entry = "<HR color=990000 size=1><font color=ff6600>$date</font><br>$content\n";
$fp = fopen("comments.txt", 'r');
$filedata = fread($fp, filesize("comments.txt"));
fclose($fp);
print $filedata;
$filedata = $entry.$filedata ;
$f = fopen("comments.txt", 'w');
fwrite($f, "$filedata\n");
fclose($f);
?>
Posted: Thu Jan 30, 2003 8:46 pm
by wickedest
thanks man, i works
