0

enter image description here

I basically want to search for a file on my computer. I know how to search but is there a fast way of searching a name and an extension without flooding my script with more than 2 for loops? the names (eg.. file,virus,node,misc) and the extensions will be added dynamically, Not through the source code.. the names will be in the thousands so i dont want to add them one by one, hence why i am doing it dynamically.

i was thinking:

foreach($names as $i){ if (file_exists($i.".exe" | $i.".py" | $i.".js" | $i.".html" | )){ //echo true or false}} 

Like i said. I will be adding in extensions dynamically also. Would it be worth it having the code long with file_exists(20 thousand extensions) or just add them with a form?

Would it be a for loop inside another for loop?

3
  • You want to search the entire filesystem or just a certain directory/subdirectory? How often will you be doing this search? How often will the files change? Commented Apr 4, 2013 at 17:31
  • certain directory, i'm looking for the proof of concept. Commented Apr 4, 2013 at 17:34
  • Are you wanting a solution that is only specific to a certain OS? Commented Apr 4, 2013 at 17:36

2 Answers 2

1

If your code is on a linux server and you have the program 'locate', I would consider using that instead. It will save you a lot of load on your server and will return results a lot faster.

Sign up to request clarification or add additional context in comments.

Comments

0

There is a way using the Spl Iterators.

The following example is taken from the documentation of RecursiveDirectoryIterator. It searches for a file called 'Yourfile.py':

$filename = 'Yourfile.py'; $directory = new RecursiveDirectoryIterator('path/to/search_root/'); $iterator = new RecursiveIteratorIterator($directory); $regexiterator = new RegexIterator( $iterator, '/^' . preg_quote($filename) . '$/', RecursiveRegexIterator::GET_MATCH ); foreach($regexiterator as $fileinfo) { var_dump($fileinfo); } 

2 Comments

how would that search for a .py file? I'm too noob to understand how regex works at the moment.
Have added $filename variable. Should be easier to use now. Even without having knowledge of regexes