How can the PHP code be structured to handle both mandatory form fields validation and file type validation before sending an email through the form mailer?

To handle both mandatory form fields validation and file type validation before sending an email through a form mailer in PHP, you can first check if the mandatory fields are filled out using if statements and then validate the file type using the $_FILES superglobal array. If the validations pass, proceed with sending the email.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    
    // Check if mandatory fields are filled out
    if ($name && $email && $message) {
        $file = $_FILES['attachment'];
        
        // Validate file type
        $allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
        if (in_array($file['type'], $allowedTypes)) {
            // Send email code here
            // Example: mail($to, $subject, $message, $headers);
            echo "Email sent successfully.";
        } else {
            echo "Invalid file type. Allowed types: JPEG, PNG, PDF.";
        }
    } else {
        echo "Please fill out all mandatory fields.";
    }
}
?>