Jump to content

writing to the top instead of the bottom!


ted_chou12

Recommended Posts

Hello, I know how to write to the bottom, simply use a.
however, writing to the top can be a little more difficult, can anyone help me to have a look at this:
[code]
<?php
$dataf = file("$recipients/inbox/message.txt");
if ($message != "" && $recipients !="" && $subject !="" && $invalid == FALSE){$file = fopen("$recipients/inbox/message.txt","w+");$write = fwrite($file,"$username#$name#$subject#$datetime#$message\r\n
");foreach ($dataf as $dataf){fwrite($file, "$dataf");}
fclose($file);}
?>
[/code]
I dont see what I have done wrong with this, but this simply overwrites the file, can anyone help me and have a look at this?
Thanks, Ted.
Link to comment
https://forums.phpfreaks.com/topic/31391-writing-to-the-top-instead-of-the-bottom/
Share on other sites

change the w+ to r+
eg.
[code]
<?php
$dataf = file("$recipients/inbox/message.txt");
if ($message != "" && $recipients !="" && $subject !="" && $invalid == FALSE){$file = fopen("$recipients/inbox/message.txt","r+");$write = fwrite($file,"$username#$name#$subject#$datetime#$message\r\n
");foreach ($dataf as $dataf){fwrite($file, "$dataf");}
fclose($file);}
?>
[/code]

this will open the file for reading and writing, places the file pointer at the beginning of the file and does not trunicate it to 0 length.

take a look at the php manual for fopen

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

from the manual [quote] w+ -Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.[/quote]
0 length means that certain arguments for the fopen() method will erase the file, and others will simply append to it.

take a look at the manual for fopen

[url=http://us2.php.net/manual/en/function.fopen.php]http://us2.php.net/manual/en/function.fopen.php[/url]

there is a table that tells you about the different arguments for the fopen method and what each one does. Some place the pointer at the top, some at the bottom, some erase the file some append. Take a look at it as the manual is a great resource for finding out what certain methods do.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.