首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >执行imap_close不起作用

执行imap_close不起作用
EN

Stack Overflow用户
提问于 2016-03-10 22:36:47
回答 2查看 206关注 0票数 8

我有与客户的页面和ajax即时通讯加载信息,他们是否给我们发送电子邮件。

代码如下所示:

代码语言:javascript
复制
$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,但这不起作用。

我的代码:

Ajax:

代码语言:javascript
复制
    $(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:

代码语言:javascript
复制
if($this->request->get['kill'] == '1'){
            imap_close($this->session->data['imap_inbox']);
            unset($this->session->data['imap_inbox']);
            $kill == 1;
            exit;
        }

但是,即使ajax被中止,并且在保存imap_open的变量上调用imap_close,页面重新加载仍然需要10-20秒,所以我假设imap没有关闭。

如何关闭imap以便页面可以立即重新加载?

EN

回答 2

Stack Overflow用户

发布于 2016-03-18 05:25:54

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

代码语言:javascript
复制
$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
EN

Stack Overflow用户

发布于 2016-03-15 21:19:31

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

现在,即使您第二次请求终止IMAP会话,foreach()循环仍将继续,直到它结束,或者当执行时间超过您的max_execution_time设置时,PHP终止它。

在任何情况下,您都需要foreach()循环中的一些东西来检查每一轮是否满足中止条件,以便切换终止当前请求并允许客户端发出新的请求。

我建议您查看PHP函数connection_aborted(),一旦客户端中止当前请求,您可以使用该函数进行检测,更广泛地说,您可以阅读有关connection handling的主题,以便更好地了解如何在PHP中处理连接和请求。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35919417

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档