简体   繁体   中英

PHP: get only one file from a directory of 10000 files based on filename containing unix stamp

I'm trying to scan directory and getting only the latest file added in the directory using filename sorting

my files have different file names but all are preceded w/ the unix_timestamp eg: 1423285600_smas293.jpg 1423285700_smas11.doc

So I know of a method to do this $files = scandir($dir, SCANDIR_SORT_DESCENDING); $newest_file = $files[0];

but that seems to load all the files into an array first.. and if i have 100K (theoretically) files? what then? Will the server become sluggish?

So i was hoping to scan and retrieve just a limited number of files into array, if that's possible --- or any other strategies that basically gets what I need done..

Regards

Well you could use opendir() and readdir() the directory entries one by one, and just remember the alphabetically biggest filename. It's what scandir() and glob() ultimately do under water. That way you don't have to load everything in memory; though you'll still have to iterate over all your theoretically 100K files:

<?php    
$biggest = false;    
if ($fp = opendir('/tmp')) {
    while ( ($entry = readdir($fp)) )
    if (! $biggest or ($entry > $biggest) )
        $biggest = $entry;
    closedir($fp);
}
print("Biggest: " . $biggest . "\n");    
?>

Ultimately it would of course be a better solution to store your files in folders by days or weeks. Your filesystem will ultimately choke when you create that many files in just one directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM