write to a txt file

General discussions related to php

Moderators: macek, egami, gesf

User avatar
WiZARD
Moderator
Moderator
Posts: 1257
Joined: Thu Jun 20, 2002 10:14 pm
Location: Ukraine, Crimea, Simferopol
Contact:

Re: write to a txt file

Postby WiZARD » Wed Jul 31, 2002 7:30 am

probe wrote: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: Select all

<?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: Select all

<?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: Select all

<?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);
?>

Jay

Postby Jay » Thu Aug 01, 2002 2:05 pm

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: Select all

<?
$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);
?>

fanlongtao
New php-forum User
New php-forum User
Posts: 2
Joined: Fri Feb 14, 2014 1:00 am

Re: write to a txt file

Postby fanlongtao » Fri Feb 14, 2014 1:05 am

You can use a+,eg:
$file_handle=fopen($file, "a+");


Return to “PHP General”

Who is online

Users browsing this forum: No registered users and 1 guest

cron