Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 687
Kyle Anderson Avatar asked May 17 '12 20:05

Kyle Anderson


3 Answers

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.

like image 69
vimist Avatar answered Oct 08 '22 19:10

vimist


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.

like image 40
hakre Avatar answered Oct 08 '22 17:10

hakre


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.

like image 42
Ginger McMurray Avatar answered Oct 08 '22 18:10

Ginger McMurray