PHP: How can I grab a single file from a directory without scanning entire directory?

吃可爱长大的小学妹 提交于 2019-12-18 11:57:32

问题


I have a directory with 1.3 Million files that I need to move into a database. I just need to grab a single filename from the directory WITHOUT scanning the whole directory. It does not matter which file I grab as I will delete it when I am done with it and then move on to the next. Is this possible? All the examples I can find seem to scan the whole directory listing into an array. I only need to grab one at a time for processing... not 1.3 Million every time.


回答1:


This should do it:

<?php
$h = opendir('./'); //Open the current directory
while (false !== ($entry = readdir($h))) {
    if($entry != '.' && $entry != '..') { //Skips over . and ..
        echo $entry; //Do whatever you need to do with the file
        break; //Exit the loop so no more files are read
    }
}
?>

readdir

Returns the name of the next entry in the directory. The entries are returned in the order in which they are stored by the filesystem.




回答2:


Just obtain the directories iterator and look for the first entry that is a file:

foreach(new DirectoryIterator('.') as $file)
{
    if ($file->isFile()) {
        echo $file, "\n";
        break;
    }        
}

This also ensures that your code is executed on some other file-system behaviour than the one you expect.

See DirectoryIterator and SplFileInfo.




回答3:


readdir will do the trick. Check the exampl on that page but instead of doing the readdir call in the loop, just do it once. You'll get the first file in the directory.

Note: you might get ".", "..", and other similar responses depending on the server, so you might want to at least loop until you get a valid file.




回答4:


do you want return first directory OR first file? both? use this:

create function "pickfirst" with 2 argument (address and mode dir or file?)

function pickfirst($address,$file) { // $file=false >> pick first dir , $file=true >> pick first file
$h = opendir($address);

     while (false !== ($entry = readdir($h))) {

          if($entry != '.' && $entry != '..' && ( ($file==false && !is_file($address.$entry)) || ($file==true && is_file($address.$entry)) )  )
          { return $entry; break; } 

} // end while
} // end function

if you want pick first directory in your address set $file to false and if you want pick first file in your address set $file to true.

good luck :)



来源:https://stackoverflow.com/questions/10642777/php-how-can-i-grab-a-single-file-from-a-directory-without-scanning-entire-direc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!