PHP file_exists and wildcard

Is there a way to write the PHP function file_exists so that it looks for a directory for a file with an arbitrary extension. For example, suppose I knew that the file was called hello, but I did not know the extension, how would I write a function that looked for a file called hello. * And returned the name of this file? As far as I can tell, file_exists will only search for a string.

Thank.

+44
php wildcard
Apr 30 '10 at 17:15
source share
4 answers

You are looking for the glob() function.

file_exists does not perform any search: it only lets you know if the fleck exists or not when you know its name.

And with PHP> = 5.3 you can use the new GlobIterator .


The following code is shown as an example with glob() :

 $list = glob('temp*.php'); var_dump($list); 

Gives me this result:

 array 0 => string 'temp-2.php' (length=10) 1 => string 'temp.php' (length=8) 


Although this one:

 $list = glob('te*-*'); var_dump($list); 

Yes, with two * ; -)

Give me:

 array 0 => string 'temp-2.php' (length=10) 1 => string 'test-1.php' (length=10) 2 => string 'test-curl.php' (length=13) 3 => string 'test-phing-1' (length=12) 4 => string 'test-phpdoc' (length=11) 
+79
Apr 30 '10 at 17:17
source share

Starting with PHP5.3, you can also use GlobIterator to search the directory with wildcards:

 $it = iterator_to_array( new GlobIterator('/some/path/*.pdf', GlobIterator::CURRENT_AS_PATHNAME) ); 

will return the full paths to all .pdf files in some / paths in the array. The above does the same thing as glob() , but iterators provide a more powerful and extensible API.

+4
Apr 30 '10 at 17:38
source share

While file_exists returns BOOLEAN, I wrote this little function that takes a search string with * to search for files ... Example:

  searchForFile("temp*"); function searchForFile($fileToSearchFor){ $numberOfFiles = count(glob($fileToSearchFor)); if($numberOfFiles == 0){ return(FALSE); } else { return(TRUE);} } 
+2
Nov 21 '11 at 16:07
source share

If you need a little more control and in pre PHP 5.3 you can use DirectoryIterator or RecursiveDirectoryIterator. Both have a great function for additional control and manipulation.

PHP docs are on DirectoryIterator and RecursiveDirectoryIterator

+1
May 01 '10 at 5:44
source share



All Articles