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
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.
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;
}
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.
The other answers might be very resource intensive on large file systems (large number of files to search through). It might be useful to create a temporary table of all the filenames (full path if necessary). Then do a like condition search of that table to get whatever the actual case is.
SELECT actual_file_name
FROM TABLE_NAME
WHERE actual_file_name LIKE 'filename_i_want'
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/*")));
glob$filename in any case i is case-insensitivecurrent returns the first filename from the arrayRemove the current() to return all matching files. This is important on case-sensitive filesystems as IMAGE.jpg and image.JPG can both exist.
//will resolve & print the real filename
$path = "CaseInsensitiveFiLENAME.eXt";
$dir = "nameOfDirectory";
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if (strtolower($path) == strtolower($entry)){
echo $entry ;
}}
closedir($handle);
}