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?
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.
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.
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.
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);
}
}