【发布时间】:2014-02-16 16:19:01
【问题描述】:
我有文件下载 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);
我使用以下:
- Apache 2.4.4
- PHP 5.4.12
- MySQL 5.6.12
- 谷歌浏览器版本 32.0.1700.107 m
- Windows 7 x64
谢谢。
【问题讨论】:
标签: php apache apache2 download