How can PHP developers ensure the security and efficiency of sending images via email in PHP?

To ensure the security and efficiency of sending images via email in PHP, developers should validate the image file type, sanitize the file name, and encode the image data before attaching it to the email. This helps prevent vulnerabilities such as file injection attacks and ensures that the image is properly handled by email clients.

// Validate image file type
$allowed_types = array('image/jpeg', 'image/png', 'image/gif');
if (!in_array($_FILES['image']['type'], $allowed_types)) {
    die('Invalid image file type.');
}

// Sanitize file name
$filename = basename($_FILES['image']['name']);
$filename = preg_replace("/[^a-zA-Z0-9\._-]/", "", $filename);

// Encode image data
$image_data = chunk_split(base64_encode(file_get_contents($_FILES['image']['tmp_name']));

// Send email with image attachment
$to = 'recipient@example.com';
$subject = 'Image Attachment';
$message = 'Please see the attached image.';
$from = 'sender@example.com';
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"boundary\"\r\n\r\n";
$headers .= "--boundary\r\n";
$headers .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$headers .= "$message\r\n\r\n";
$headers .= "--boundary\r\n";
$headers .= "Content-Type: {$_FILES['image']['type']}; name=\"$filename\"\r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; filename=\"$filename\"\r\n\r\n";
$headers .= "$image_data\r\n\r\n";
$headers .= "--boundary--";

mail($to, $subject, '', $headers);