RSS

[php][tutorial] directory sorting by file type and last modified date

18 Nov

Following code is there to list all the files within the specified directory by sorting files by file type and last modified date respectively:

<?php
function sort_by_filetype($src='.')
{
$dirFiles = array();
if ($handle = opendir($src)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$extn = explode('.',$file);
$type = $extn[count($extn)-1];
$dirFiles[$type.$file] = $file;
}
}
closedir($handle);
}
ksort($dirFiles);
return $dirFiles;
}
function sort_by_filemtime($src='.')
{
$dirFiles = array();
if ($handle = opendir($src)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$date = filemtime($file);
$dirFiles[$date.$file] = $file;
}
}
closedir($handle);
}
ksort($dirFiles);
return $dirFiles;
}
$src = '.';
echo "<br><strong>Sort By File Type</strong>";
$dirFiles = sort_by_filetype($src);
foreach($dirFiles as $file)
{
echo "<br>".$file;
}

echo "<br><strong>Sort By Time</strong>";
$dirFiles = sort_by_filemtime($src);
foreach($dirFiles as $file)
{
echo "<br>".$file;
}
?>

Thats it 🙂

Advertisements
 
Leave a comment

Posted by on November 18, 2011 in php

 

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: