User 5842
User 5842

Reputation: 3029

How to update a .txt file using PHP

My colleague and I are working on a chat application for a small Flash based game. We would like to keep our chat file as small as possible by automatically deleting old text after the file has reached a certain limit. Say the file exceeds 50 lines, we would like to delete the existing information and begin again at line 1. Is this possible?

<?php

$file = "saved.txt";
$edited_text = $_POST['new_text'];

$open = fopen($file, "a+");
fwrite($open, "\n" . $edited_text);
fclose($open);

?>

Upvotes: 1

Views: 603

Answers (2)

Aziz Saleh
Aziz Saleh

Reputation: 2707

This would work:

// Read entire file
$lines = file_get_contents('saved.txt');
// Add what you want to the beginning of array
array_unshift($lines, 'new line of text');
// Keep first 50 items
$lines = array_splice($lines, 0, 50);
// Write them back
file_put_contents('saved.txt', implode(PHP_EOL, $lines));

Will always keep the first 50 elements intact (which includes messages from new to old).

Upvotes: 0

Marc B
Marc B

Reputation: 360702

Basically something like this:

$lines = file('saved.txt');
$lines[] = 'new line of text';
array_unshift($lines); // remove first array element
file_put_contents('saved.txt', implode(PHP_EOL, $lines));
  1. Read the file into an array, one line per array element
  2. Append your new line(s) of text
  3. Remove as many lines from the start of the array as necessary
  4. dump array back out to file as text.

Upvotes: 2

Related Questions