What best practice should be followed when filtering file types in a directory using PHP?
When filtering file types in a directory using PHP, it is important to ensure that only allowed file types are included while filtering out any unwanted file types. This can be achieved by checking the file extension of each file in the directory against a list of allowed file extensions. Any file that does not match the allowed file extensions should be excluded from the filtered list.
$directory = '/path/to/directory';
$allowedExtensions = ['jpg', 'png', 'gif'];
$files = scandir($directory);
$filteredFiles = [];
foreach ($files as $file) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if (in_array($extension, $allowedExtensions)) {
$filteredFiles[] = $file;
}
}
print_r($filteredFiles);