What are the best practices for efficiently filtering files based on name patterns, file size, and MIME type using PHP functions like glob, fileinfo, and array_filter?

When filtering files based on name patterns, file size, and MIME type in PHP, it is best to use a combination of functions like glob, fileinfo, and array_filter. First, use glob to retrieve a list of files based on a specific pattern. Then, use fileinfo to determine the MIME type of each file. Finally, use array_filter to efficiently filter the files based on the desired criteria.

// Define the directory path and pattern
$directory = 'path/to/directory';
$pattern = '*.txt';

// Get a list of files based on the pattern
$files = glob($directory . '/' . $pattern);

// Filter the files based on file size and MIME type
$filteredFiles = array_filter($files, function($file) {
    $fileInfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = $fileInfo->file($file);
    $size = filesize($file);

    // Example filtering criteria: files with MIME type text/plain and size less than 1MB
    if ($mime === 'text/plain' && $size < 1048576) {
        return true;
    }

    return false;
});

// Output the filtered files
print_r($filteredFiles);