PHP Case Insensitive Version of file_exists()

后端 未结 14 1495
忘掉有多难
忘掉有多难 2020-11-30 07:47

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 strtolowe

14条回答
  •  半阙折子戏
    2020-11-30 08:28

    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;
    }
    

提交回复
热议问题