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
Just ran across this today, but didn't like any of the answers here, so I thought I would add my solution ( using SPL and the regex iterator )
function _file_exists( $pathname ){
if(file_exists($pathname)) return $pathname;
try{
$path = dirname( $pathname );
$file = basename( $pathname );
$Dir = new \FilesystemIterator( $path, \FilesystemIterator::UNIX_PATHS );
$regX = new \RegexIterator($Dir, '/(.+\/'.preg_quote( $file ).')$/i', \RegexIterator::MATCH);
foreach ( $regX as $p ) return $p->getPathname();
}catch (\UnexpectedValueException $e ){
//invalid path
}
return false;
}
The way I am using it is like so:
$filepath = 'path/to/file.php';
if( false !== ( $filepath = _file_exists( $filepath ))){
//do something with $filepath
}
This way it will use the built in one first, if that fails it will use the insensitive one, and assign the proper casing to the $filepath
variable.
I tuned the function a lil bit more. guess this better for use
function fileExists( $fileName, $fullpath = false, $caseInsensitive = false )
{
// Presets
$status = false;
$directoryName = dirname( $fileName );
$fileArray = glob( $directoryName . '/*', GLOB_NOSORT );
$i = ( $caseInsensitive ) ? "i" : "";
// Stringcheck
if ( preg_match( "/\\\|\//", $fileName) ) // Check if \ is in the string
{
$array = preg_split("/\\\|\//", $fileName);
$fileName = $array[ count( $array ) -1 ];
}
// Compare String
foreach ( $fileArray AS $file )
{
if(preg_match("/{$fileName}/{$i}", $file))
{
$output = "{$directoryName}/{$fileName}";
$status = true;
break;
}
}
// Show full path
if( $fullpath && $status )
$status = $output;
// Return the result [true/false/fullpath (only if result isn't false)]
return $status;
}