Get the filename of the newest file in a directory

<?php /** * Get the filename of the newest file in a directory. * Optionally specify a filename extension on which to limit the search. * @param string $directory The name of the directory to search * @param string $extension If not empty, only files with this extension will be searched * @return string * @author Sunny Walker <www.miraclesalad.com> */ function getNewestFile($dir, $extension='') { $handle = opendir($dir); $return = ''; $the_time = 0; while ($file = readdir($handle)) { $fname = $dir.'/'.$file; if ($file != '..' && $file != '.' && !is_dir($fname)) { $ext = strtolower(substr(strrchr($file,'.'),1)); $ftime = filemtime($fname); if (($extension=='' || ($extension!='' && $ext==$extension)) && $ftime>$the_time) { $the_time = $ftime; $return = $fname; } } } return $return; } //getNewestFile() ?>

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.