What are some best practices for creating a contact form that allows users to send images as attachments using PHP?

When creating a contact form that allows users to send images as attachments using PHP, it is important to properly handle file uploads and validate the file type to ensure security. One common best practice is to use the PHP `$_FILES` superglobal to access the uploaded file data and move the file to a designated folder on the server. Additionally, you can use PHP's `mail()` function to send the email with the attached image file.

<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){
    $file = $_FILES['image'];

    $target_dir = "uploads/";
    $target_file = $target_dir . basename($file["name"]);

    if(move_uploaded_file($file["tmp_name"], $target_file)){
        $to = "recipient@example.com";
        $subject = "New Image Attachment";
        $message = "Please see the attached image.";
        $headers = "From: sender@example.com";
        
        $attachment = chunk_split(base64_encode(file_get_contents($target_file)));
        $filename = $file["name"];
        
        $headers .= "\r\nMIME-Version: 1.0\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary=\"boundary\"\r\n";
        $headers .= "--boundary\r\n";
        $headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
        $headers .= "Content-Transfer-Encoding: 7bit\r\n";
        $headers .= "\r\n$message\r\n";
        $headers .= "--boundary\r\n";
        $headers .= "Content-Type: application/octet-stream; name=\"$filename\"\r\n";
        $headers .= "Content-Transfer-Encoding: base64\r\n";
        $headers .= "Content-Disposition: attachment\r\n";
        $headers .= "\r\n$attachment\r\n";
        $headers .= "--boundary--";

        if(mail($to, $subject, "", $headers)){
            echo "Email sent successfully!";
        } else {
            echo "Email sending failed.";
        }
    } else {
        echo "File upload failed.";
    }
}
?>