Search code examples
phphtmlemailimap

Php - imap_delete - Delete just selected email


I have a script that prints out all inbox emails fetched from an imap server. I have added a delete submit button that when pressed needs to delete just the email that belongs to the button. However, the script right now, deletes all the email when any delete button is pressed. A simplified code below:

<?php    
foreach($emails as $email_number) {
?>
 <form method="post">
        <th class="tg-031e"><input type="submit" name="delete_inbox" value="Delete"></th>
        </form>

<?php
if(isset($_POST['delete_inbox'])){
$check = imap_mailboxmsginfo($imap);
echo "Messages before delete: " . $email_number . "<br />\n";
imap_delete($imap, $email_number);
$check = imap_mailboxmsginfo($imap);
echo "Messages after  delete: " . $check->Nmsgs . "<br />\n";
imap_expunge($imap);
$check = imap_mailboxmsginfo($imap);
echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";
}
}?>

Any ideas in how I could just delete the email selected by pressing delete button? Also why do I have to refresh the page two times in order to see the changes after deletion?


Solution

  • It appears there is no association between the deletion form for an email and the email itself. PHP has no way of knowing what exact email you wish to delete.

    As suggested before, one idea is to put the email's i.d within the value of the submit button next to each email.

    You can then take that from the post data of the delete_inbox input.

     <?php
        if(isset($_POST['delete_inbox'])){
        // Retrieve email i.d value from delete_inbox button
        $email_to_delete = $_POST['delete_inbox'];
        $check = imap_mailboxmsginfo($imap);
    
    
    echo "Messages before delete: " . $email_number . "<br />\n";
    // Delete selected email
    imap_delete($imap, $email_to_delete);
    $check = imap_mailboxmsginfo($imap);
    echo "Messages after  delete: " . $check->Nmsgs . "<br />\n";
    imap_expunge($imap);
    $check = imap_mailboxmsginfo($imap);
    echo "Messages after expunge: " . $check->Nmsgs . "<br />\n";
    }
    
    foreach($emails as $email_number) {
    ?>
     <form method="post">
            <th class="tg-031e"><button type="submit" name="delete_inbox" value="<?php echo $email_number; ?>">Delete</button></th>
            </form>
    
    <?php }?>
    

    Note: I have also removed the $_POST section of the code out of the foreach loop. I don't see any reason for it to be there.