PHP Case Insensitive Version of file_exists()

Viewed 30511

I'm trying to think of the fastest way to implement a case insensitive file_exists function in PHP. Is my best bet to enumerate the file in the directory and do a strtolower() to strtolower() comparison until a match is found?

14 Answers

AbraCadaver's answer with +7 rating is incorrect, I do not have enough reputation to comment under it, so here is correct solution, based on his answer:

$result = count(preg_grep('/\/'.preg_quote($filename)."$/i", glob("$path/*")));

AbraCadaver's answer is incorrect, because it returns true if you test against file foo.jpg and files like anytext_foo.jpg exist.

Just ran across this today, but didn't like any of the answers here, so I thought I would add my solution ( using SPL and the regex iterator )

function _file_exists( $pathname ){
    if(file_exists($pathname)) return $pathname;

    try{
        $path = dirname( $pathname );
        $file = basename( $pathname );

        $Dir = new \FilesystemIterator( $path, \FilesystemIterator::UNIX_PATHS );
        $regX = new \RegexIterator($Dir, '/(.+\/'.preg_quote( $file ).')$/i', \RegexIterator::MATCH);

        foreach ( $regX as $p ) return $p->getPathname();

    }catch (\UnexpectedValueException $e ){
        //invalid path
    }
    return false;
}

The way I am using it is like so:

 $filepath = 'path/to/file.php';

 if( false !== ( $filepath = _file_exists( $filepath ))){
      //do something with $filepath
 }

This way it will use the built in one first, if that fails it will use the insensitive one, and assign the proper casing to the $filepath variable.

Related