Deleting oldest entries from text file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
AshrakTheWhite
Forum Commoner
Posts: 69
Joined: Thu Feb 02, 2006 6:47 am

Deleting oldest entries from text file

Post by AshrakTheWhite »

hi again another possibly nuubish question!

Now i have a viable PHP program that does some calculations and puts the eventual written text into a .txt file on server side, however eventually the file will be of massive proportions, hence id like to find a way to keep only the 10 newest entries. Any ideas or code to achive this goal is welcome :)

heres the program i have:

Code: Select all

<html>
   <head>
   </head>
   <body>
      <pre>
         <?php
            $arr = file("/var/www/test.txt");
            foreach ($arr as $line) {
               print $line;
            }

         ?>
      </pre>

<?php

   $input1 = $_POST['msg1'];
   $input2 = $_POST['msg2'];
   $input3 = $_POST['msg3'];
   $input4 = $_POST['msg4'];
   $iive = $input1-$input2;
   $filename = '/var/www/test.txt';
   $kuupaev = date("l dS \of F Y h:i:s A");

$somecontent = "-------------------------------------------" . '<br>';
$somecontent .= $kuupaev . '<br>';
$somecontent .= 'Sisse tuli: ' . $input1 . '<br>';
$somecontent .= 'Välja läks: ' . $input2 . '<br>';
$somecontent .= 'Iiive: ' . $iive . '<br>';
$somecontent .= 'Katkiseid Arvuteid: ' . $input3 . '<br>';
$somecontent .= 'Korras Arvuteid: ' . $input4 . '<br>';
$somecontent .= "-------------------------------------------" . '<br>' . '<br>';
   echo $somecontent;


if (is_writable($filename)) {
   if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
   }
   if (fwrite($handle, $somecontent) === FALSE) {
       echo "Cannot write to file ($filename)";
       exit;
   }
   echo "Success.";
   fclose($handle);
} else {
   echo "The file $filename is not writable";
}


?>

   </body>
</html>
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

You can take the contents of a file into an array, as you are doing with file(), then pop/push/chunk/split the array of the comments you wish to remove, then implode() the array into a string and fwrite() or file_put_contents() back to the file :)
Post Reply