Alex
Alex

Reputation: 9265

Check if file exists when unknown extension

I know the directory and filename but not the file's extension. What is the best way to determine if /somedir/file.jpg exists if all I have to go on is /somedir/file? My current method would be using a directory iterator to get the filenames of all the files in the directory without the extension and breaking on the first match e.g. if file === file.

Upvotes: 3

Views: 1421

Answers (1)

Lawrence Cherone
Lawrence Cherone

Reputation: 46610

You can use RecursiveCallbackFilterIterator to filter out only matching basename minus the extension:

<?php
$file = './somedir/file';

$filter = new \RecursiveCallbackFilterIterator(
    new \RecursiveDirectoryIterator(dirname($file), \FilesystemIterator::SKIP_DOTS), 
    function ($current, $key, $iterator) use ($file) {
        return !$current->isDir() && $current->getBasename('.'.$current->getExtension()) == basename($file);
    }
);
$iterator = new \RecursiveIteratorIterator($filter);

Then on that you can, check found:

if (iterator_count($iterator) > 0) {
    //found
} else {
    //not found
}

or, get values:

// get the first filepath
$filename = $iterator->getPathname();

// or loop it if your expecting multiple extensions
foreach($iterator as $file) {
   echo $file->getPathname().PHP_EOL;
}

And it that fails, you could always use glob()

if (!empty(glob($file.".*"))) { 
    echo 'File found'; 
}

Upvotes: 3

Related Questions