How can PHP developers effectively handle file size and MIME type validation for uploaded files?

To effectively handle file size and MIME type validation for uploaded files in PHP, developers can use the $_FILES superglobal to access the file information, check the file size using the 'size' key, and verify the MIME type using functions like finfo_file() or mime_content_type(). By validating both the file size and MIME type, developers can ensure that only allowed files are uploaded to the server.

// Validate file size
$maxFileSize = 2 * 1024 * 1024; // 2MB
if ($_FILES['file']['size'] > $maxFileSize) {
    echo 'File size exceeds the limit.';
    exit;
}

// Validate MIME type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $_FILES['file']['tmp_name']);
finfo_close($finfo);

$allowedMimeTypes = ['image/jpeg', 'image/png', 'application/pdf'];
if (!in_array($mimeType, $allowedMimeTypes)) {
    echo 'Invalid file type.';
    exit;
}

// Continue with file upload process