Search code examples
phpfileglob

Get latest 15 files in a directory that are recently added to it php


Suppose there's a directory named "abc"

This directory contains number of files. Out of all these files, I just want latest "X" or latest 15 files in an array(if possible using glob function) in php.

Every help will be greatly appreciable.


Solution

  • // directory for searching files
    
    $dir = "/etc/php5/*";
    
    // getting files with specified four extensions in $files
    
    $files = glob($dir."*.{extension1,extension2,extension3,extension4}", GLOB_BRACE);
    
    // will get filename and filetime in $files
    
    $files = array_combine($files, array_map("filemtime", $files));
    
    // will sort files according to the values, that is "filetime"
    
    arsort($files);
    
    // we don't require time for now, so will get only filenames(which are as keys of array)
    
    $files = array_keys($files);
    
    $starting_index = 0;
    $limit = 15;
    
    // will limit the resulted array as per our requirement
    
    $files = array_slice($files, $starting_index,$limit);
    
    // will print the final array
    
    echo "Latest $limit files are as below : ";
    print_r($files);
    

    Please improve me, if am wrong