PHP Case Insensitive Version of file_exists()
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 casei
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.
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;
}