What are some best practices for optimizing PHP code when sending multiple email attachments, such as avoiding repetition using DRY principles?
When sending multiple email attachments in PHP, it's important to avoid repetition and follow the DRY (Don't Repeat Yourself) principle to optimize the code. One way to achieve this is by using arrays to store the file paths of the attachments and then loop through the array to attach them to the email.
<?php
// Array of file paths for attachments
$attachments = [
'/path/to/attachment1.pdf',
'/path/to/attachment2.jpg',
'/path/to/attachment3.docx'
];
// Loop through the attachments array and attach each file to the email
foreach ($attachments as $attachment) {
$file_name = basename($attachment);
$file_content = file_get_contents($attachment);
$file_encoded = base64_encode($file_content);
$mail->addStringAttachment($file_encoded, $file_name);
}
?>