brain Posted April 9, 2007 Share Posted April 9, 2007 Hi, I'm trying edit a script called shoutbox and it simply just adds a name and comment to a txt file on a new line and includes it into my webpage via php. My problem is that it adds the new comment to the bottom... I need it to add that comment to the top in a accending order. $lines = file($file_path); $handle = file_connect($file_path, 'a'); if(@fwrite($handle, $message['name']." | ".$message['url']." | ".$message['message']."\n")) { I've tried w+ but it erases the previous comments added to the data.txt file. Does anyone know how I would add a line to the top of the data.txt file without first erasing it? Link to comment https://forums.phpfreaks.com/topic/46228-how-to-add-to-the-first-line-of-a-txt-file/ Share on other sites More sharing options...
simcoweb Posted April 9, 2007 Share Posted April 9, 2007 Try r+ Read/Write. Starts at the beginning of the file. Link to comment https://forums.phpfreaks.com/topic/46228-how-to-add-to-the-first-line-of-a-txt-file/#findComment-224779 Share on other sites More sharing options...
clown[NOR] Posted April 9, 2007 Share Posted April 9, 2007 dont do that... i've tried it and all it does is that it overwrites.. so you have to add the new shout to bottom of the file, and then when you read it you have to reverse the array... this is the code i use to write to the file: <?php $phps_sbname = $_REQUEST['sbname']; $phps_sburl = $_REQUEST['sburl']; $phps_sbmessage = $_REQUEST['sbmsg']; if ($phps_sbname == '') { echo 'Please enter a name'; } elseif ($phps_sbmessage == '') { echo 'Please enter a message'; } else { if ($phps_sburl == '') { $phps_newshout = "\n<table border=0 width=100% cellspacing=0 cellpadding=0><tr><td bgcolor=#FFFFFF><strong>" . $phps_sbname . ":</strong> " . $phps_sbmessage . "</td></tr><tr><td bgcolor=#999999 height=1></td></tr></table>"; } elseif ($phps_sburl != '') { $phps_newshout = "\n<table border=0 width=100% cellspacing=0 cellpadding=0><tr><td bgcolor=#FFFFFF><strong><a href=" . $phps_sburl . " target=_blank>" . $phps_sbname . "</a>:</strong> " . $phps_sbmessage . "</td></tr><tr><td bgcolor=#999999 height=1></td></tr></table>"; } $phps_sbfh = fopen("filename.txt", "ab"); fwrite($phps_sbfh,$phps_newshout); fclose($phps_sbfh); Header("Location: URL"); } ?> this is the file that reads the file: <?php $phps_sbfh = @fopen('filename.txt', "r"); if ($phps_sbfh) { while (!feof($phps_sbfh)) { $phps_sblines[] = fgets($phps_sbfh, 4096); } fclose($phps_sbfh); $phps_sbresult = array_reverse($phps_sblines); $phps_sbresult = array_slice($phps_sbresult, 0, 20); foreach($phps_sbresult as $phps_shout) echo $phps_shout; } ?> Link to comment https://forums.phpfreaks.com/topic/46228-how-to-add-to-the-first-line-of-a-txt-file/#findComment-224784 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.