PHP Curl - 如果用户断开连接,操作将中止

时间:2012-10-31 17:20:00

标签: php curl

我这里有这段代码,允许用户通过我的服务器下载文件:

$ch_2 = curl_init();
curl_setopt($ch_2, CURLOPT_USERAGENT, 'Mozilla/4.0');
curl_setopt($ch_2, CURLOPT_URL, $download_link);
curl_setopt($ch_2, CURLOPT_AUTOREFERER, true);
curl_setopt($ch_2, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch_2, CURLOPT_COOKIESESSION, false);
curl_setopt($ch_2, CURLOPT_FAILONERROR, true);
curl_setopt($ch_2, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch_2, CURLOPT_FORBID_REUSE, true);
curl_setopt($ch_2, CURLOPT_FRESH_CONNECT, true);
curl_setopt($ch_2, CURLOPT_NOSIGNAL, true);
curl_setopt($ch_2, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch_2, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch_2, CURLOPT_TIMEOUT, 86400);
curl_setopt($ch_2, CURLOPT_LOW_SPEED_LIMIT, 10240);
curl_setopt($ch_2, CURLOPT_LOW_SPEED_TIME, 60);
curl_setopt($ch_2, CURLOPT_MAX_RECV_SPEED_LARGE, 500);
curl_exec($ch_2);
$curl_errno_2 = curl_errno($ch_2);
curl_close($ch_2);

Theese文件(链接在$ download_link中)非常大,大约1-3 GB。

此代码工作正常,但我的问题是,当用户断开连接或中止下载时,脚本不会停止,直到服务器收到完整文件($ download_link)。

如果我设置“ignore_user_abort(true)”,那么脚本会停止,但是可以在脚本中检查客户端断开连接或下载中止并可以处理吗?例如,更新MySQL数据库条目还是其他什么?

我知道我可以使用“readfile()”或fopen,例如fread更改此代码,但我会(并且必须)使用此cURL代码。

是否可以检查此用户断开连接或下载中止,因为我只允许用户按IP address建立一个下载连接?因此,如果他们中止下载我无法更新我的MySQL数据库以管理此IP地址的下载连接。

1 个答案:

答案 0 :(得分:2)

您可以注册关机功能。当脚本完成,用户中止或调用exit()或die()时,将调用此方法。 http://php.net/manual/en/function.register-shutdown-function.php

例如,(来自php.net):

<?php
    function shutdown()
    {
        // This is our shutdown function, in
        // here we can do any last operations
        // before the script is complete.

        echo 'Script executed with success', PHP_EOL;
    }

    register_shutdown_function('shutdown');
?>

这是你最接近的。

  

“因为我只允许用户为每个IP地址建立一个下载连接?”

我建议你这样做:

  1. 使用APC存储当前正在下载内容的IP地址
  2. 注册关闭功能以从APC中删除IP地址,允许他们下载其他内容
相关问题