2014-02-16 48 views
0

我有文件下载PHP脚本。该脚本可以下载最大4GB +的大文件。实际上,用户将经常会取消下载过程或在下载时关闭浏览器窗口。PHP Connection_Aborted()仅适用于有时

因此,我必须在已经开始的下载过程因任何原因而中止时注册。对此的最佳解决方案看起来是通过connection_aborted()函数监视连接。

'connection_aborted()'似乎对下载取消或关闭我的浏览器窗口有反应。我的问题是,它不会以100%的精度做出反应。它注册了约50%的取消下载或关闭的浏览器。如果未检测到连接中止,则只需在服务器上继续下载,就好像浏览器不会取消它一样。

请问我的代码是否存在漏洞和错误?我需要了解,是什么原因导致的行为:

// empty and turn off output buffering 
    ob_flush(); 
    flush(); 


    // never expire this download script 
    set_time_limit(0); 

    fseek($fileObject, $seek_start); 

    while(!feof($fileObject)) 
    { 
     //usleep(100000); 

     //print(@fread($fileObject, $chunkSize)); 
     echo(@fread($fileObject, $chunkSize)); 

     // gradually output buffer to avoid memory problems by downloading large files 
     ob_flush(); 
     flush(); 

     // check if the client was disconnected 
     // important for cancelled or interrupted downloads 
     if (Connection_Aborted()) 
     { 
      ChromePhp::log("Connection Aborted"); 

      // sent to the database that the connection has been aborted 
      $result = mysqli_query($dbc, "UPDATE current_downloads SET connection_aborted=TRUE WHERE user_id=1;"); 

      // close the database connection 
      mysqli_close($dbc); 

      // close the open file 
      @fclose($fileObject); 

      exit(json_encode(array("result" => false, "error" => "Connection with the client was aborted."))); 
     } 

     $nLoopCounter++; 
     $transferred += $chunkSize; 
     $downloadPercentage = (($nLoopCounter * $chunkSize)/$fileSize) * 100; 

     $result = mysqli_query($dbc, "UPDATE current_downloads SET progress_percent=$downloadPercentage, transferred=$transferred, connection_aborted=$strConnectionAborted, iteration=$nLoopCounter WHERE user_id=1;"); 
     if($result == false) 
     { 
      // close the database connection 
      mysqli_close($dbc); 

      // close the file 
      fclose($handle); 

      // prepare output message 
      $outputArray = array("result" => 0, "message" => "Error Processing Database Query"); 

      // output the message 
      echo json_encode($outputArray); 
      exit; 
     } 
    } 

    // file save was a success 
    @fclose($fileObject); 

我使用以下命令:

  • 的Apache 2.4.4
  • PHP 5.4.12
  • 的MySQL 5.6.12
  • Google Chrome版本32.0.1700.107 m
  • Windows 7 x64

谢谢。

回答

0

添加功能connection_status,然后再次尝试

if(connection_status()!=0||connection_aborted()!=0||){ 
    //your code 
} 
+0

Xiongji您好,感谢您的答复。我测试了修改过的if((connection_status()!= 0)||(connection_aborted()!= 0))',但不幸的是没有改变。错误日志也没有显示任何错误。 –