Php sort files by last modified

Hi, in this post we'll discuss about a method to sort files in a directory/folder by last modified date in php. Though php language comes with a rich set of sorting functions such as sort() rsort() ksort() etc., none of them will directly suits for this purpose. In order to sort files in a folder, we should first copy the filenames from the said directory to an array and then define our custom sorting function to sort those files by last modified date. PHP's usort() is such function which we can use to sort arrays by the way we define.

Php sort files by last modified

How to Sort Files by Last Modified Date in PHP

Let me show you by an example how to perform this file sorting. Say I want to sort all the 'JPEG' image files from a directory according to their recently modified date and time. Here's the php code to do it.

<?php
// get current directory path
$dirpath = getcwd();
// set file pattern
$dirpath .= "\*.jpg";
// copy filenames to array
$files = array();
$files = glob($dirpath);

// sort files by last modified date
usort($files, function($x, $y) {
    return filemtime($x) < filemtime($y);
});

foreach($files as $item){
    echo basename($item) . " => Last Modified On " . @date('F d, Y, H:i:s', filemtime($item)) . "<br/>";
}
?>

// produces output

// image001.jpg => Last Modified On November 04, 2015, 17:53:24
// image002.jpg => Last Modified On October 23, 2015, 21:03:26
// image003.jpg => Last Modified On October 09, 2015, 21:23:15
// image004.jpg => Last Modified On July 03, 2015, 14:49:07
// image005.jpg => Last Modified On July 02, 2015, 22:32:03
// image006.jpg => Last Modified On February 02, 2015, 15:35:34

The above php script sorts out '*.jpg' files from current working directory.

The method glob() will return an array of file names with full path matching the given pattern.

And filemtime() will get the last modified date and time of a file in unix timestamp.

The function usort() will sort the given array by value based upon the user defined comparison function. In this case the comparison is based upon the last-modified date.

To sort all the files in a folder, just use the file pattern like this,

$dirpath .= "\*.*";

If you want to sort the files from different folders then change the $dirpath variable accordingly.

Recommended Read:

  • How to Auto Complete Textbox from DB using PHP and MySQL
  • How to Convert Multi-Dimensional Array to XML File in PHP

And that was all about sorting files by last modified date in php.

Using the below action I gather a list of files and display them. I need to be able to sort the files by last modified date. Is there a simple way in PHP or using ZEND to order the items by last modified? If you know of a easier way to get the files and order them using ZEND; please let me know.

public function imagesAction()
{
    $this->_helper->layout->disableLayout();

    $results = array();

    $handler = opendir(APPLICATION_PATH . '/../public/images/blog');

    while ($file = readdir($handler)) {
        if ($file != "." && $file != ".." && $file != '.svn') {
            $results[] = $file;
        }
    }

    closedir($handler);

    $this->view->data = $results;
}

I have tried doing

$this->view->data = ksort($results);
$this->view->data = asort($results);

But those just remove the entire list of files from the view and they stop showing up.

asked Nov 26, 2012 at 20:46

ILikeTurtlesILikeTurtles

9894 gold badges15 silver badges47 bronze badges

3

public function imagesAction()
{
    $this->_helper->layout->disableLayout();

    $results = array();

    $handler = opendir(APPLICATION_PATH . '/../public/images/blog');

    while ($file = readdir($handler)) {
        if ($file != "." && $file != ".." && $file != '.svn') {
            $results[] = array('file' => $file, 'time' => filemtime($file));
        }
    }

    closedir($handler);

    uasort($results, function($file1, $file2) {
        if ( $file1['time'] == $file2['time'] )
           return 0;
        return $file1['time'] < $file2['time'] ? -1 : 1;
    });

    $this->view->data = $results;
}

answered Nov 26, 2012 at 20:52

4

You can use a DirectoryIterator ( http://php.net/manual/en/class.directoryiterator.php ) to easy iterate over the files in a directory and get the properties of each (including last modified time).

You could simply instantiate the iterator, iterate through it and sort the items into an array of your choosing.

answered Nov 26, 2012 at 20:52

Php sort files by last modified

Mike BrantMike Brant

69.4k10 gold badges97 silver badges101 bronze badges

Use the last modified date as the key:

while ($file = readdir($handler)) {
    if ($file != "." && $file != ".." && $file != '.svn') {
        $s = stat($file);
        if (!is_array($results[$s['mtime']]) {
             $results[$s['mtime']] = array();
        }
        $results[$s['mtime']][] = $file;
    }
}

Then use ksort to sort by key:

ksort($results);

Every item of $results now holds an array of filenames that are modified at the same time.

answered Nov 26, 2012 at 20:51

Php sort files by last modified

Bart FriederichsBart Friederichs

32.2k15 gold badges96 silver badges186 bronze badges

1

How to get last modified information of a file using PHP?

The filemtime() function is an inbuilt function that returns the last modification of the file content. It returns as a UNIX timestamp of the last modification time of a file and returns false on failure. The filename is passed by filemtime() as a parameter.

How to sort files in PHP?

PHP Sorting Arrays.
sort() - sort arrays in ascending order..
rsort() - sort arrays in descending order..
asort() - sort associative arrays in ascending order, according to the value..
ksort() - sort associative arrays in ascending order, according to the key..

How to sort files by date in PHP?

Once this is set up, you can simply call sort() and the algorithm will compare by the mod times first, then break ties using the unique filenames. $result = []; foreach (glob('path/to/files/*. swf') as $file) { $result[] = [filemtime($file), $file]; } sort($result); var_export($result);

How does Usort work in PHP?

The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array in a new manner. This function assigns new integral keys starting from zero to the elements present in the array and the old keys are lost.