PHP Case Insensitive Version of file_exists()

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?


Solution 1:

I used the source from the comments to create this function. Returns the full path file if found, FALSE if not.

Does not work case-insensitively on directory names in the filename.

function fileExists($fileName, $caseSensitive = true) {

    if(file_exists($fileName)) {
        return $fileName;
    }
    if($caseSensitive) return false;

    // Handle case insensitive requests            
    $directoryName = dirname($fileName);
    $fileArray = glob($directoryName . '/*', GLOB_NOSORT);
    $fileNameLowerCase = strtolower($fileName);
    foreach($fileArray as $file) {
        if(strtolower($file) == $fileNameLowerCase) {
            return $file;
        }
    }
    return false;
}

Solution 2:

This question is a few years old but it is linked to several as duplicates, so here is a simple method.

Returns false if the $filename in any case is not found in the $path or the actual filename of the first file returned by glob() if it was found in any case:

$result = current(preg_grep("/^".preg_quote($filename)."$/i", glob("$path/*")));
  • Get all files in the path glob
  • Grep for the $filename in any case i is case-insensitive
  • current returns the first filename from the array

Remove the current() to return all matching files. This is important on case-sensitive filesystems as IMAGE.jpg and image.JPG can both exist.

Solution 3:

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.