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

前端 未结 4 471
别跟我提以往
别跟我提以往 2020-12-29 08:59

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.

相关标签:
4条回答
  • 2020-12-29 09:15

    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.

    0 讨论(0)
  • 2020-12-29 09:20

    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 :)

    0 讨论(0)
  • 2020-12-29 09:29

    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.

    0 讨论(0)
  • 2020-12-29 09:34

    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.

    0 讨论(0)
提交回复
热议问题