Just use the DirectoryIterator class.
foreach (new DirectoryIterator('../pictures/uploads') as $fileInfo) {
if ($fileInfo->isDot()) continue;
if (stripos($fileInfo->getFilename(), 'profile' . $id) !== false) {
var_dump($fileInfo->getExtension());
}
}
The DirectoryIterator class is available since PHP 5.3.6.
A more detailed example could be a DirectoryIterator instance used by a FilterIterator instance to just output the desired files. Th given example requires a minimum of PHP 7.4. If you 're using a PHP version smaller than 7.4 remove the type hints for the class properties.
class MyFileFilter extends FilterIterator
{
protected string $filename;
public function __construct(Iterator $iterator, $filename)
{
$this->filename = $filename;
parent::__construct($iterator);
}
public function accept(): bool
{
$info = $this->getInnerIterator();
return stripos($info->getFilename(), $this->filename) !== false;
}
}
The FilterIterator class is available since PHP 5.1. The above shown extension takes an Iterator and searches for a given filename and returns the SplFileInfo object, if the filename matches.
How to use it:
$directory = new DirectoryIterator('../pictures/uploads');
$filename = 'picture' . $id;
$filter = new MyFileFilter($directory, $filename);
foreach ($filter as $file) {
var_dump($file->getExtension());
}
The foreach loop is basically the filter, that only returns files, that match the given filename. Every returned file is a SplFileInfo instance. With this you can use the SplFileInfo::getExtension() method to get the file extension.
Last but not least comes the GlobIterator class which is available since PHP 5.3. It 's the easiest way to iteratate over a given path with placeholders.
$filesystem = new GlobIterator('../pictures/uploads/profile' . $id . '.*');
foreach ($filesystem as $file) {
var_dump($file->getExtension());
}