Jump to content

write to the top of a txt file, no over-writes.


tomcommathe

Recommended Posts

Title kind of says it all, I am new to PHP and I am trying to creating a little text area input box that when you click submit the *.txt file doesn't get overwritten and the new information is placed at the top of the file.

 

The Write Code:

<?php
if (isset($_POST['submit'])) {
$filename = "name.txt";
$open = fopen($filename, "r+");
$name = $_POST['name'];
$sayWhat = $_POST['sayWhat'];
$hidden = $_POST['hidden'];
fwrite($open, "Name:\t$name <br />");
fwrite($open, "What?!:\n $sayWhat \n");
fwrite($open, "$hidden\r <br>");
fclose($open);
}
?>

 

The Display Code:

<?
$filename = "name.txt";
$fp=fopen($filename,'r');
$content=fread($fp,filesize($filename));
fclose($fp);

$content = $content;

echo $content;
?>

 

The test page, don't mind the shitty layout I am working on that too: http://mopedstl.com/phpTest/test2.php

<?php
if (isset($_POST['submit'])) {
$filename = "name.txt";
$open = fopen($filename, "r+");

$content = fread($fp,filesize($filename));
$newContent = "Name:\t$name <br />";
$newContent .= "What?!:\n $sayWhat \n";
$newContent .= "$hidden\r <br>";

$newContent .= $content;

fwrite($open, $newContent);
fclose($open);
?>

There are two ways to do this (well actually three if you consider storing the information in a database so that you can retrieve it in any order you want.)

 

1) The easy way - write (append) the new information to the end of the file and reverse the order when you display it. To display the information, use the file() function to read the lines into an array and use the array_reverse() function to reverse the order.

 

2a) The hard way, without any failsafe file error recovery - read the existing file using the method of your choice. Recreate the file and write the new content, followed by the old content.

 

2b) The hard way, with failsafe file error recovery - write the new content to a temporary file, then read and append the existing content to the temporary file. After the temporary file has been written and closed without any errors, delete the old file and rename the temporary file to be the actual file in use.

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.