How can MIME types and file extensions be properly validated when processing file uploads in PHP?

When processing file uploads in PHP, it is important to validate both the MIME type and file extension to ensure that only allowed file types are accepted. This helps prevent security vulnerabilities such as allowing users to upload malicious files. One way to validate MIME types is by using the finfo_file() function, and for file extensions, you can use the pathinfo() function.

// Validate MIME type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
if ($mime !== 'image/jpeg' && $mime !== 'image/png') {
    // Handle invalid MIME type
}

// Validate file extension
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$allowed_extensions = array('jpg', 'jpeg', 'png');
if (!in_array($ext, $allowed_extensions)) {
    // Handle invalid file extension
}