How can PHP developers ensure the security and reliability of email attachments in their applications?

To ensure the security and reliability of email attachments in PHP applications, developers should validate file types, scan attachments for malware, and sanitize file names to prevent directory traversal attacks. Additionally, using secure file upload methods and implementing proper file handling techniques can help mitigate potential security risks.

// Validate file type
$allowedTypes = ['pdf', 'doc', 'docx', 'txt'];
$extension = pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION);
if (!in_array($extension, $allowedTypes)) {
    die('Invalid file type. Allowed types are pdf, doc, docx, txt.');
}

// Scan attachment for malware
$attachmentPath = $_FILES['attachment']['tmp_name'];
if (exec('clamscan ' . $attachmentPath)) {
    die('Attachment contains malware.');
}

// Sanitize file name
$fileName = preg_replace("/[^a-zA-Z0-9._-]/", "", $_FILES['attachment']['name']);
$uploadPath = '/path/to/upload/directory/' . $fileName;

// Move uploaded file to secure directory
if (move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadPath)) {
    echo 'Attachment uploaded successfully.';
} else {
    echo 'Failed to upload attachment.';
}