What are best practices for decoding and saving email attachments in PHP when using IMAP?

When decoding and saving email attachments in PHP using IMAP, it is important to properly handle encoding types such as base64 or quoted-printable. One common approach is to use the `imap_fetchstructure` function to get the attachment details and then decode the attachment using functions like `base64_decode` or `quoted_printable_decode`. Finally, the decoded attachment can be saved to a file on the server.

// Connect to the IMAP server
$mailbox = '{imap.example.com:993/imap/ssl}INBOX';
$username = 'email@example.com';
$password = 'password';
$inbox = imap_open($mailbox, $username, $password);

// Get the number of messages in the inbox
$numMessages = imap_num_msg($inbox);

// Loop through each message
for ($i = 1; $i <= $numMessages; $i++) {
    // Get the structure of the message
    $structure = imap_fetchstructure($inbox, $i);

    // Check if the message has attachments
    if (isset($structure->parts) && count($structure->parts)) {
        // Loop through each part of the message
        foreach ($structure->parts as $partNum => $part) {
            // Check if the part is an attachment
            if (isset($part->disposition) && strtolower($part->disposition) == 'attachment') {
                // Get the attachment data
                $attachmentData = imap_fetchbody($inbox, $i, $partNum+1);

                // Decode the attachment
                $attachmentData = base64_decode($attachmentData);

                // Save the attachment to a file
                file_put_contents('attachments/attachment_'.$i.'_'.$partNum.'.pdf', $attachmentData);
            }
        }
    }
}

// Close the connection to the IMAP server
imap_close($inbox);