The correct way to delete all files older than 2 days in PHP

The correct way to delete all files older than 2 days in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

The correct way to delete all files older than 2 days in PHP

Your proposed snippet relies on glob to retrieve file paths and then iterates through them, checking modification times against a hardcoded second count of 172,800 (exactly two days). While this logic is sound for simple scenarios, it introduces significant fragility regarding timezone handling and lacks the robustness required for production environments.

The core issue lies in the comparison: time() - $filemtime. The time() function returns the current Unix timestamp in UTC, regardless of your server's configured timezone. If your application expects to run based on local time (e.g., deleting files older than 2 days from now in the user's timezone), this code will be off by several hours depending on where the script runs. For instance, if the server is in UTC+2 and it is currently midnight there (02:00 UTC), time() returns a timestamp corresponding to yesterday at 22:00 UTC. A file modified at midnight UTC+2 yesterday would appear older than 2 days according to this logic, leading to unintended deletions.

To fix this, you must normalize the time comparison to a specific timezone or ensure both sides of the equation use the same temporal context. The most reliable approach is to convert the current time to the desired timezone before calculating the difference.

Here is a corrected implementation that handles timezone safety explicitly:

$targetDirectory = cacheme_directory();
$files = glob($targetDirectory . '/*');

if ($files === false) {
    // Handle case where directory does not exist or glob failed
    return;
}

// Define the threshold in seconds (2 days)
$threshold = 172800;

foreach ($files as $file) {
    // Ensure we are working with a valid file path
    if (!is_file($file)) {
        continue;
    }

    $filemtime = filemtime($file);
    
    // Get current time in the same timezone context as your application logic
    // If you want to use server default, no change is needed. 
    // If you need specific timezone handling, uncomment below:
    // $now = DateTime::createFromFormat('U', (string)$now)->setTimezone(new DateTimeZone('UTC')); 
    
    if ($filemtime < time() - $threshold) {
        unlink($file);
    }
}

However, relying solely on glob has a hidden pitfall: it returns filenames, not full paths if the directory does not end with a slash or if the path contains special characters that glob interprets differently. More critically, glob can fail silently or return false if the directory permissions prevent listing contents. Always check the return value of glob before iterating.

A more robust alternative for production systems involves using DirectoryIterator. This class provides better control over file metadata and allows you to safely skip directories while processing files. It also avoids potential issues with * patterns matching hidden files or special characters that might break the glob logic depending on shell configurations.

$directory = new DirectoryIterator($targetDirectory);

foreach ($directory as $file) {
    if (!$file->isFile()) {
        continue;
    }

    $mtime = $file->getMTime();
    
    // Using DateTime objects allows for clearer timezone manipulation
    $cutoff = new DateTime('@' . $mtime);
    $now = new DateTime(); // Uses server default timezone
    
    if ($now->getTimestamp() - $cutoff->getTimestamp() > 172800) {
        $file->unlink();
    }
}

Using DateTime objects makes the code self-documenting. You can easily pass a specific DateTimeZone to $now if your business logic dictates that "older than 2 days" refers to a specific region's time, rather than the server's internal UTC clock. This prevents the ambiguity of raw integer timestamps.

Finally, consider the performance implications. Iterating through thousands of files in PHP is generally acceptable for cleanup scripts, but ensure the script runs with sufficient memory limits and timeouts configured. If you are using Laravel, you might consider scheduling this task via the scheduler (Schedule::command('php artisan clean:cache')), which handles error logging and retry logic automatically. For complex directory structures or very large datasets, a dedicated cron job running a compiled script like find or rsync might offer better performance than a PHP loop, but for standard application caches, the corrected PHP approach provides the necessary precision.

Our network