Get the latest file addition in a directory

Viewed 48636

How to get the latest file name, or the file path that is added into a directory?

6 Answers

Here's how you can do it using DirectoryIterator:

foreach(new DirectoryIterator('/path/to/read') as $item) {
    if ($item->isFile() && (empty($file) || $item->getMTime() > $file->getMTime())) {
        $file = clone $item;
    }
}

The resulting contents of $file is an instance of the DirectoryIterator class and as such you have access to all of it's methods. To simply get the full path of the result you can do:

echo $file->getPathname();
Related