...

View Full Version : append to top of file and reload



loonatik
04-07-2003, 01:52 PM
Using the basic syntax for appending files:

$filename = "message.txt";
$fp = fopen($filename, "a") or die("couldn't open $filename");
flock($fp, LOCK_EX);
fwrite($fp, "hello, this is testing");
flock($fp, LOCK_UN);
fclose($fp);
//reload to see new message. how?

The text is appended at the end of whatever is already in message.txt. How can I make it so that it appends at the top of the file instead? So that new messages are at the top.

Also, what is the code to tell the page to reload?


thanks very much.

Galdo
04-07-2003, 02:30 PM
Have a look at this page:

http://www.php.net/manual/en/function.fopen.php

It shows the different ways you can open a file, so maybe try it with r+ instead?



$filename = "message.txt";
$fp = fopen($filename, "r+") or die("couldn't open $filename");
flock($fp, LOCK_EX);
fwrite($fp, "hello, this is testing");
flock($fp, LOCK_UN);
fclose($fp);
//reload to see new message. how?

loonatik
04-07-2003, 05:22 PM
I'm using this as a message board/guestbook type. So when I use r+ it writes over; and when I use a or a+, it just appends to the end of file. I"ve added the flock($fp, LOCK_EX); but it doesn't apply with a/a+.

$filename = "message.txt";
$fp = fopen($filename, "r+") or die("couldn't open $filename");
flock($fp, LOCK_EX);
fseek($fp, 0, SEEK_SET);
fwrite($fp, "hello, this is testing");
flock($fp, LOCK_UN);
fclose($fp);

Is the solution more complex than I think it is?

firepages
04-07-2003, 06:18 PM
you can't write to the top of the file without overwriting the existing content.

the normal workaround is to open the file , get the contents add your new content and resave...



<?
$filename='file.txt';
$content = 'blah';
$new = $content . "\n" . implode( '' , file( $filename ) );
$fp =fopen($filename,'w');
//etc save the $new content
?>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum