tags:

views:

43

answers:

4

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?

+1  A: 

In Unix file names are case sensitive, so you won't be able to do a case insensitive existence check without listing the contents of the directory.

Adam Byrtek
+1  A: 

For a pure PHP implementation, yes. There's an example in the comments for the file_exists function.

The other option would be to run your script on a case insensitive file system.

deceze
Thanks! Ended up using this in my answer.
Kirk
+1  A: 

Your approach works.
Alternatively you can use glob to get the list of all files and directories in the present working directory in an array, use array_map to apply strtolower to each element and then use in_array to check if your file(after applying strtolower) exists in the array.

codaddict
A: 

I used the source from the comments to create this function. If case sensitive is set to false, then the full path file that matches the requested filename is returned.

function fileExists($fileName, $caseSensitive = true) {
    // Handle case insensitive requests
    if(!$caseSensitive) {
        if(file_exists($fileName)) {
            return true;
        }
        $directoryName = dirname($fileName);
        $fileArray = glob($directoryName . '/*');
        $fileNameLowerCase = strtolower($fileName);
        foreach($fileArray as $file) {
            if(strtolower($file) == $fileNameLowerCase) {
                return $file;
            }
        }
        return false;
    }
    else {
        return file_exists($fileName);
    }
}
Kirk
Wouldn't it be nice to ALWAYS return a full filename? It's kind of weird to sometimes get a boolean and sometimes a useful path when a match is found.
Emil Vikström