【问题标题】:PHP Curl - Operation abort if the user disconnectedPHP Curl - 如果用户断开连接,则操作中止
【发布时间】:2012-12-01 02:17:26
【问题描述】:

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

$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);

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

这段代码运行良好,但我的问题是,当用户断开连接或中止下载时,脚本不会停止,直到服务器收到完整文件 ($download_link)。

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

我知道我可以通过使用“readfile()”或 fopen、fread 来更改此代码,但我将(并且必须)使用此 cURL 代码。

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

【问题讨论】:

    标签: php curl


    【解决方案1】:

    您可以注册关机功能。这将在脚本完成、用户中止或调用 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 地址,从而允许他们下载其他内容

    【讨论】:

    • 如果我设置了 "ignore_user_abort(false)" 并且客户端连接断开,这是否有效?
    • 是的,然后关闭功能将执行,我还在最后添加了关于使用 APC 的额外位(我在看到您更新的问题后添加)
    • 然而,php 在尝试执行输出之前无法检测到远程中止。
    • 我正要使用这个解决方案,然后我发现我可以在使用 cURL 的类中使用 __destruct() 函数来完成同样的事情
    猜你喜欢
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多