How can PHP developers ensure the security of email attachments sent through PHP scripts?

PHP developers can ensure the security of email attachments sent through PHP scripts by validating file types, sanitizing file names, and storing attachments in a secure directory outside of the web root to prevent direct access.

// Example code snippet to ensure security of email attachments
$attachment = $_FILES['attachment'];

// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
if (!in_array($attachment['type'], $allowedTypes)) {
    die('Invalid file type.');
}

// Sanitize file name
$fileName = preg_replace("/[^A-Za-z0-9.]/", "", $attachment['name']);

// Store attachment in secure directory
$uploadDir = '/path/to/secure/directory/';
if (!move_uploaded_file($attachment['tmp_name'], $uploadDir . $fileName)) {
    die('Failed to upload attachment.');
}

// Attach file to email
$mail->addAttachment($uploadDir . $fileName);