Sort Files by Last Modified Date in PHP

On 11/13/2015

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.

sort-files-by-last-modified-date-in-php

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.

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

Recommended Read:

1 comment:

  1. This technical post helps me to improve my skills set, thanks for this wonder article I expect your upcoming blog, so keep sharing...
    PHP Training in Chennai|PHP Course in Chennai

    ReplyDelete

Contact Form

Name

Email *

Message *