How can the imap_expunge function be used to ensure messages marked for deletion are actually purged in PHP?

To ensure messages marked for deletion are actually purged in PHP using the imap_expunge function, you need to call this function after marking the messages for deletion with imap_delete. This will permanently remove the messages from the mailbox.

$mailbox = imap_open("{hostname:port/imap}INBOX", "username", "password");
$emails = imap_search($mailbox, 'DELETED');

if ($emails) {
    foreach ($emails as $email_number) {
        imap_delete($mailbox, $email_number);
    }
    imap_expunge($mailbox);
}

imap_close($mailbox);