2016-03-10 62 views
8

我有客戶的頁面和ajax im正在加載他們是否向我們發送電子郵件的信息。執行imap_close不起作用

代碼如下所示:

$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 
} 

但也有大約20-30個客戶在一個頁面上,所以需要proccess有時約10-20秒,以顯示我是無法優化的過程。

但是,當客戶端嘗試重新加載頁面時,它仍然在等待imap_search完成之前等待,因此重新加載時可能需要20秒才能重新加載頁面。

我試圖用beforeunload函數中止ajax函數並關閉imap但這不起作用。

我的代碼:

阿賈克斯:

$(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; 
     } 

但即使ajax被中止,imap_close被稱爲可變控股imap_open,它仍然需要10 20秒重新加載頁面,所以我假設imap沒有關閉。

如何關閉imap以便頁面可以立即重新加載?

+0

您是否有任何imap日誌可以在您刷新時查看它是否關閉連接?它通常覺得你需要在這一點上處理imap調優代碼。 – mkaatman

+0

可能存在會話鎖定的問題; – itzmukeshy7

回答

1

如果我理解正確,耗時的代碼位於foreach()循環內。

現在,即使你犯了一個第二個請求殺IMAP會話,即foreach()循環將繼續,直到它完成 PHP殺死它如果(何時)執行時間超過你的max_execution_time設置。

在任何情況下,你都需要在你的foreach()循環中有一些東西,它會檢查每一輪是否符合中止條件,以便切斷當前請求並允許客戶端創建新的請求。

我建議你看看PHP函數connection_aborted(),你可以用它來檢測一旦客戶將中止當前的要求,更普遍,你可以對connection handling話題讀得到的連接和請求,如何更好的感覺在PHP中處理。

2

我會建議通過創建使休息文件殺死它:

$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){ 
     clearstatcache(); //Can't use the cached result. 
    if(file_exists('/tmp/kill_imap.'.$this->session->id)) break; //making the assumption that /tmp and session->id are set, but the idea is a temporary folder and a unique identifier to that session. 
    $emails = imap_search($inbox, 'FROM ' . $email); 
    // Processing info 
} 
if(file_exists('/tmp/kill_imap.'.$this->session->id)) unlink('/tmp/kill_imap.'.$this->session->id); 

然後在你的出口AJAX,只需撥打一個PHP腳本,只是簡單地創建該文件。它會打破你的循環並刪除文件。