Search code examples
phptrimfilesize

PHP delete first row of file till threshold is reached


I want to trim my log-files to 7KB. But the trimming just run once and the filesize will also not be updated.

Here is the code:

$thresholdKB = "7";
$files = glob('logs/*.{log}', GLOB_BRACE);

foreach($files as $file) {
    $filesizeKB = filesize("$file") / 1024;
    if ($filesizeKB > $thresholdKB){
        while ($filesizeKB > $thresholdKB) {
            $filesizeKB = filesize("$file") / 1024;

            $lines = file("$file"); 
            unset($lines[0]); 
            $fp = fopen("$file", 'w'); 
            fwrite($fp, implode('', $lines)); 
            fclose($fp);
        }
    }
}

Solution

  • The results of filesize are cached. You need to call clearstatcache() after updating the file.

    https://www.php.net/manual/en/function.clearstatcache.php