Search code examples
phpfile-get-contentsstrposunlink

Exclude unlink if string contains X


I have a question relating to some file deletions. Lets start with the code

$dir = "./reporting/live-metrics/";
foreach (glob($dir."*") as $file) {
$live = file_get_contents($file);
if (strpos($live, 'CORO') !== false) {
}
if (filemtime($file) < time() - 3 * 60) {
    $exclude[] = $live;
    unlink($file);
    }
}

I am pretty sure my use of file_get_contents and strpos is incorrect. My attempt is that multiple files are created in live-metrics and the only constant is on line 2 of the file (either CORO or EMER). I am attempting to exclude any file that contains CORO within the file while deleting any other file after 3 minutes modified time.


Solution

  • Combine the two conditions

    if (strpos($live, 'CORO') === false && filemtime($file) < time() - 3 * 60) {
        $exclude[] = $live;
        unlink($file);
    }
    

    You could also write:

    if (strpos($live, 'CORO') !== false {
        continue;
    }
    

    continue skips the rest of the loop body and goes to the next iteration.