Execute imap_close not working

Viewed 237

I have page with customers and with ajax im loading info on whether they send us email or not.

Code looks like this:

$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'email';
$password = 'password';

$this->session->data['imap_inbox'] = $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());

 foreach($customers as $customer){
     $emails = imap_search($inbox, 'FROM ' . $email);
     // Processing info
 }

But there are roughly 20-30 customers on one page, so the proccess takes sometimes about 10-20 seconds to show and I was unable to optimize the process.

But when client tries to reload a page, it is still waiting before imap_search finishes, so when reloading it could take 20 seconds before the page is actually reloaded.

I have tried to abort the ajax with beforeunload function and close the imap but this is not working.

My code:

Ajax:

    $(window).bind('beforeunload',function(){
    imap_email.abort(); // the ajax is succesfully aborted(as showed in console), yet the page still takes considerable time to reload

    $.ajax({
        type: 'GET',
        url: 'getimapmails&kill=1',
        async:false
    }); // ajax call to the same function to call imap_close 

});

PHP:

if($this->request->get['kill'] == '1'){
            imap_close($this->session->data['imap_inbox']);
            unset($this->session->data['imap_inbox']);
            $kill == 1;
            exit;
        }

But even though the ajax is aborted and imap_close is called on variable holding imap_open, it still takes 10-20 seconds for page to reload, so I'm assuming the imap was not closed.

How do I close the imap so the page can reload immediately?

2 Answers
Related