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++;
}