2014-02-16 52 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))',但不幸的是沒有改變。錯誤日誌也沒有顯示任何錯誤。 –