May 13, 2013

PHP: clear a text file if it exceeds 50 lines

ToxicMouse’s Question:

OK, what am I missing? I am trying to clear a file if it exceeds 50 lines.

This is what I have so far.

$file = 'idata.txt';
$lines = count file($file);
if ($lines > 50){
$fh = fopen( 'idata.txt', 'w' );
fclose($fh);
}
$file = 'idata.txt';
$lines = count(file($file));
if ($lines > 50){
$fh = fopen( 'idata.txt', 'w' );
fclose($fh);
}

You have an error in your syntax, it should be count(file($file)); Using this method is not recommended for larger file as it loads the file onto the memory. Thus, it will not be helpful in case of large files. Here is another way to solve this:

$file="idata.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  if($linecount > 50) {
      //if the file is more than 50
      fclosh($handle); //close the previous handle

      // YOUR CODE
      $handle = fopen( 'idata.txt', 'w' ); 
      fclose($handle);  
  }
  $linecount++;
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!