PHP: Simple Script to Retrieve the Newest File in a Folder CodeUnit 31 OCT 2011

Not particularly efficient for very large folders of course, but this simple little script will successfully check the last modified timestamp of files in a folder to determine the newest most fresh file contained within, before forcing a page redirect to the file, useful if you say want to show for instance the latest image file contained in a directory.

//determing the latest file in a folder and redirecting to it

//get the correct file path to use
$documentRoot =$_SERVER['DOCUMENT_ROOT']; 
if (key_exists('SUBDOMAIN_DOCUMENT_ROOT',$_SERVER)){ 
	$documentRoot = $_SERVER['SUBDOMAIN_DOCUMENT_ROOT']; 
} 
//set the folder path to the target folder
$folder = $documentRoot . DIRECTORY_SEPARATOR . 'myfolder'; 

//variable to hold the newest file path
$newestFile = ''; 

//loop through the target directory. If file, compare the modified time to the currently set newest file. Update accordingly.
if (is_dir($folder)){ 
	foreach (scandir($folder) as $node) { 
		$nodePath = $folder . DIRECTORY_SEPARATOR . $node; 
		if (!is_dir($nodePath)){ 
		    if ($newestFile == ''){ 
		        $newestFile = $nodePath; 
		    } else { 
		        if (filemtime($nodePath) > filemtime($newestFile)){ 
			$newestFile = $nodePath; 
		        } 
		    } 
		} 
	} 
} 

//force redirect to the latest file, otherwise print an error message
if (is_file($newestFile)){ 
	header('location: ' . str_replace($documentRoot . DIRECTORY_SEPARATOR . 'comics','http://' . $_SERVER['SERVER_NAME'] . '/myfolder',$newestFile)); 
} else { 
	echo '

Unable to determine latest file in the specified folder.

'; }

Like I said, not the most efficient of methods for very large folders, but simple enough to do the job for those smaller ones!

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.