PHP: Sort Files from Directory & Order them by Filemtime()

Posted on October 5, 2008, under PHP,  Bookmark it

This is a function that selects files from a directory and orders them by the last time they were changed, in ascending or descending order. The snippet also calculates how much time passed since the file’s content was changed.

function Sort_Directory_Files_By_Last_Modified($dir, $sort_type = 'descending', $date_format = "F d Y H:i:s.")
{
$files = scandir($dir);

$array = array();

foreach($files as $file)
{
	if($file != '.' && $file != '..')
	{
		$now = time();
		$last_modified = filemtime($dir.$file);

		$time_passed_array = array();

		$diff = $now - $last_modified;

		$days = floor($diff / (3600 * 24));

		if($days)
		{
		$time_passed_array['days'] = $days;
		}

		$diff = $diff - ($days * 3600 * 24);

		$hours = floor($diff / 3600);

		if($hours)
		{
		$time_passed_array['hours'] = $hours;
		}

		$diff = $diff - (3600 * $hours);

		$minutes = floor($diff / 60);

		if($minutes)
		{
		$time_passed_array['minutes'] = $minutes;
		}

		$seconds = $diff - ($minutes * 60);

		$time_passed_array['seconds'] = $seconds;

	$array[] = array('file'         => $file,
		             'timestamp'    => $last_modified,
		             'date'         => date ($date_format, $last_modified),
		             'time_passed'  => $time_passed_array);
	}
}

usort($array, create_function('$a, $b', 'return strcmp($a["timestamp"], $b["timestamp"]);'));

if($sort_type == 'descending')
{
krsort($array);
}

return array($array, $sort_type);
}

Here’s an usage example of this function:

$dir  = '/home/public_html/my_directory/';

$array = Sort_Directory_Files_By_Last_Modified($dir);

// Info Array
$info = $array[0];

// Sort Type
$sort_type = $array[1];

echo '<h3>'.$dir.'</h3>';

echo 'Order by: Last Modified ('.$sort_type.')<br />';

foreach($info as $key => $detail)
{
	echo '<h4 style="color: #3B4F9F;">'.$detail['file'].'</h4>';

	echo 'Last Modified: '.$detail['date'].'<br />';

	$time_passed = '';

	foreach($detail['time_passed'] as $type => $value)
	{
	$time_passed .= $value." ".$type.", ";
	}

	$time_passed = "<span style='color: #377420;'>".rtrim($time_passed, ", ")."</span> ago";

	echo $time_passed."nn";

}


Sample Output

NOTE: If you are using a PHP Version lower than 5, replace the code from the 3rd line (function file):

$files = scandir($dir);

with this one:

$dh  = opendir($dir);
$files = array();
while (false !== ($filename = readdir($dh)))
{
    $files[] = $filename;
}

This is a PHP4 alternative to scandir().

Do you wish to receive the latest updates as soon as they are posted? Get our RSS Feed or Subscribe to the Newsletter!

Get our RSS Feed!

5 Replies to "PHP: Sort Files from Directory & Order them by Filemtime()"

  1. Its a superb script. Its working fine. Keep it up.

  2. Fantastic! Works straightaway! Thanks a million!

  3. error for me

    Warning: filemtime() [function.filemtime]: stat failed for

    on line 12 of function

    $last_modified = filemtime($dir.$file);

  4. Thank u so much!
    Its working fine

  5. Thank you… this is very useful script.

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)