read and sort directory contents in php
<p>if you need to read in the contents of a directory in php and sort it by date</p>
<pre>header('Content-Type: application/json');
$dir = "./html/";
$filetype = ".html";
$out = "";
$filesarray[] = "";
// Open a directory, and read its contents
if (isdir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false) {
if (strpos($file, $filetype) !== false) {
if($file > " ") {
// add to an array to be sorted by filetime
$filesarray[filemtime($dir.$file)] = $file;
}
}
}
closedir($dh);
}
}
krsort($filesarray);
foreach ($filesarray as $filedate => $file) {
if($file > " ") {
$out .= "<div class='link'>";
$out .= "<div class='filedatetime'>";
$out .= date("F d Y H:i:s.",filemtime($dir.$file));
$out .= "</div>";
$out .= filegetcontents($dir.$file);
$out .= "</div>";
}
}
//asort($dirarray);
//echo jsonencode(arrayfilter($dirarray));
echo $out;
</pre>