pasine
pasine

Reputation: 11543

Faster way to match filename in a folder containing thousend of files

I was using this readdir to find a file in a folder

$handler = opendir($folder);

while ($file = readdir($handler)) {

  if ($file != "." && $file != ".." && substr($file,0,7) == '98888000') {
    print $file. "<br />";
  }

}

but since I have tons of files in the folder it takes some minutes to complete the request: how can I fast it up?
Consider I'm on PHP5 + IIS.

I've tried even glob()

foreach (glob($folder.98888000."*.pdf") as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}

but it returned nothing.

Upvotes: 3

Views: 1334

Answers (2)

hakre
hakre

Reputation: 197732

First check if $folder contains a / at it's end or not, this could have caused your problem with glob (the pattern was just wrong). So add things as needed and remove those things not needed to write a propper glob pattern:

$folder = realpath($folder);
foreach (glob($folder.'/98888000*', GLOB_NOSORT) as $filename) {
    echo "$filename size " . filesize($filename) . "\n";
}

I used the GLOB_NOSORT for speed reasons.

Instead of using glob() you can make use of the GlobIterator class:

$folder = realpath($folder);
$query = $folder.'/98888000*';
foreach(new GlobIterator($query) as $file)
{
    $name = $file->getFilename();
    $size = $file->getSize();
    echo "$name size $size \n";
}

Related: Iterate over specific files in a directory and 9 Ways to Iterate Over a Directory in PHP.

Upvotes: 1

Joey
Joey

Reputation: 354496

What about glob maybe? It finds files matching a pattern:

glob('98888000*')

might work.

If you need opendir and readdir, then you might want to have a look at fnmatch.

Upvotes: 2

Related Questions