Wednesday, 3 January 2018

How to get Latest File Name from a Directory with PHP

Here is the code that will return the last file name uploaded to a directory using PHP:
<?php
//get the lastest file uploaded in excel_uploads/
$path = "uploads";
$latest_ctime = 0;
$latest_filename = '';    
$d = dir($path);
while (false !== ($entry = $d->read())) {
$filepath = "{$path}/{$entry}";
//Check whether the entry is a file etc.:
    if(is_file($filepath) && filectime($filepath) > $latest_ctime) {
    $latest_ctime = filectime($filepath);
    $latest_filename = $entry;
    }//end if is file etc.
}//end while going over files in excel_uploads dir.
echo $latest_filename;
?>

0 comments:

Post a Comment