我有文件下载PHP脚本。该脚本可以下载最大4GB +的大文件。实际上,用户通常会在下载时取消下载过程或关闭浏览器窗口。
因此,我必须在已经启动的下载过程因任何原因中止时进行注册。对此的最佳解决方案是通过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);
我使用以下内容:
谢谢。
答案 0 :(得分:0)
添加功能connection_status
,然后重试
if(connection_status()!=0||connection_aborted()!=0||){
//your code
}