【问题标题】:Execute imap_close not working执行 imap_close 不起作用
【发布时间】:2016-06-25 11:17:15
【问题描述】:

我有客户页面和 ajax 我正在加载关于他们是否向我们发送电子邮件的信息。

代码如下:

$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 位客户,因此显示过程有时需要大约 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 以便页面可以立即重新加载?

【问题讨论】:

  • 您是否有任何 imap 日志可以在您刷新以查看它是否正在关闭连接时查看?通常感觉你现在需要对代码进行 imap 调整。
  • 可能存在会话锁定问题;

标签: javascript php jquery ajax imap


【解决方案1】:

我建议通过创建一个导致中断的文件来终止它:

$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 脚本。它会打破你的循环并删除文件。

【讨论】:

    【解决方案2】:

    如果我理解正确的话,耗时的代码位于 foreach() 循环中。

    现在,即使您再次请求终止 IMAP 会话,foreach() 循环仍将继续,直到它完成 PHP 终止它 if(并且when) 执行时间超过你的 max_execution_time 设置。

    在任何情况下,您都需要在 foreach() 循环中检查每一轮是否满足中止条件,以便快速终止当前请求并允许客户端创建新请求。

    我建议您查看 PHP 函数 connection_aborted(),您可以使用它来检测客户端是否中止当前请求,更一般地,您可以阅读 connection handling 的主题以更好地了解连接方式并且请求在 PHP 中处理。

    【讨论】:

      猜你喜欢
      • 2014-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多