How to get the newest file in a directory in php

How to get the newest file in a directory in php

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

Stefan Bogdanescu

Founder & Senior Architect

Finding the Newest File in a Directory with PHP

Hardcoding file paths works fine for static scripts, but it breaks the moment your application needs to handle a rolling workflow where filenames change dynamically. In the scenario you described, you have a directory full of CSV exports named with dates, and you need to automatically identify the most recent one without manually updating your code every time a new export drops in.

The core logic here is simple: determine which filename represents the latest modification date within the target folder. PHP provides the scandir() function to retrieve a list of files and the filemtime() function to get the Unix timestamp of when a file was last modified. By comparing these timestamps, you can programmatically select the newest entry.

Here is a robust pattern for implementing this logic:

$directory = 'data';
$files = scandir($directory);

if ($files) {
    $newestFile = null;
    $newestTime = 0;

    foreach ($files as $file) {
        // Skip . and .. directory entries
        if ($file == '.' || $file == '..') {
            continue;
        }

        $path = $directory . '/' . $file;

        // Check if it is a regular file, not a subdirectory or symlink
        if (is_file($path)) {
            $mtime = filemtime($path);

            if ($mtime > $newestTime) {
                $newestTime = $mtime;
                $newestFile = $file;
            }
        }
    }

    if ($newestFile !== null) {
        $myFile = $directory . '/' . $newestFile;
        $fh = fopen($myFile, 'r');

        // Handle the case where the file couldn't be opened
        if ($fh === false) {
            throw new RuntimeException("Unable to open the newest CSV file: " . $myFile);
        }
    } else {
        throw new RuntimeException("No files found in the data directory.");
    }
}

This approach avoids relying on filename patterns alone. While your filenames contain date tags that might suggest alphabetical sorting works, filesystem behavior can be unpredictable. Some systems sort directories lexicographically, while others might not guarantee order based on name length or special characters. Relying solely on scandir() without filtering by modification time risks selecting a file with a later name but an older actual timestamp if the naming convention isn't perfectly strict.

There are specific edge cases to consider when deploying this logic. First, ensure you are checking for subdirectories within your target folder. The is_file() check in the example explicitly ignores directories, preventing errors that occur when trying to open a folder path as a file stream. Second, be mindful of file permissions. If the script runs under a specific user context (like a web server running as www-data) but the files were written by a different user, fopen() might fail even if the timestamp logic identified the correct file.

If you are building this on top of the Laravel framework, you can leverage its filesystem helper to wrap these operations safely and cleanly. You can use Storage::disk()->allFiles('data') combined with lastModified() to achieve the same result without manual timestamp comparisons. This abstraction handles permission checks and path resolution internally, reducing the surface area for security issues or configuration errors.

For high-volume processing environments, scanning a directory every time is computationally expensive. If your application runs frequently, consider caching the list of files or using a database to track file metadata instead of querying the filesystem directly on every request. This trade-off adds a layer of complexity but significantly improves performance under load.

Our network