How can the imap_search function be used to filter emails based on their ID in PHP?

To filter emails based on their ID using the imap_search function in PHP, you can pass the ID as a search criterion in the form 'HEADER Message-ID <id>'. This will return an array of email message numbers that match the specified ID.

$server = &#039;{imap.example.com:993/imap/ssl}INBOX&#039;;
$username = &#039;your_username&#039;;
$password = &#039;your_password&#039;;

$mailbox = imap_open($server, $username, $password);

$email_id = &#039;12345&#039;; // ID of the email to filter

$search_criteria = &#039;HEADER Message-ID &lt;&#039; . $email_id . &#039;&gt;&#039;;

$email_numbers = imap_search($mailbox, $search_criteria);

if ($email_numbers) {
    foreach ($email_numbers as $email_number) {
        $header = imap_headerinfo($mailbox, $email_number);
        echo &#039;Email with ID &#039; . $email_id . &#039; found in message number &#039; . $email_number . &#039; with subject: &#039; . $header-&gt;subject . PHP_EOL;
    }
} else {
    echo &#039;No emails found with ID &#039; . $email_id;
}

imap_close($mailbox);