Skip to content
Advertisement

PHP file_exists and wildcard

Is there a way to write the PHP file_exists function so that it searches a directory for a file with an arbitrary extension. For instance, suppose I knew that a file were called “hello”, but I didn’t know the extension, how would I write a function that searched 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.

Thanks.

Advertisement

Answer

You’re looking for the glob() function.

file_exists doesn’t do any kind of search : it only allows one to know whether a file exists or not, when knowing its name.

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


As an example with `glob()`, the following portion of code :
JavaScript

Gives me this output :

JavaScript

While this one :
JavaScript

Yes, with two * 😉

Will give me :

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement