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
Having found this page from a quick google I used Kirk's solution, however it's slow if you call it multiple times on the same directory, or on a directory that has many files in. This is due to it looping over all the files each time, so I optimised it a little:
function fileExists($fileName) {
static $dirList = [];
if(file_exists($fileName)) {
return true;
}
$directoryName = dirname($fileName);
if (!isset($dirList[$directoryName])) {
$fileArray = glob($directoryName . '/*', GLOB_NOSORT);
$dirListEntry = [];
foreach ($fileArray as $file) {
$dirListEntry[strtolower($file)] = true;
}
$dirList[$directoryName] = $dirListEntry;
}
return isset($dirList[$directoryName][strtolower($fileName)]);
}
I dropped the flag to check for case insensitivity as I assume you'd just use file_exists if you didn't need this behaviour, so the flag seemed redundant. I also expect that if you're doing anything beyond a trivial script you'd want to turn this into a class to get more control over the directory list caching, e.g. resetting it, but that's beyond the scope of what I needed and it should be trivial to do if you need it.