【问题标题】:Copy vs Curl to save external file at my server复制 vs Curl 将外部文件保存在我的服务器上
【发布时间】:2018-08-08 09:59:53
【问题描述】:

哪种方式将外部文件保存到我的服务器最快。为什么以及如何?

使用卷曲:

$ch = curl_init();
$fp = fopen ($local_file, 'w+');
$ch = curl_init($remote_file);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_exec($ch);
curl_close($ch);
fclose($fp);

使用复制:

copy($extFile, "report.csv");

【问题讨论】:

    标签: php file curl


    【解决方案1】:

    它主要取决于协议(例如,如果它是本地文件,则 copy() 会更快),但是由于您说的是“远程文件”,因此 curl 可能会更快。您正在使用CURLOPT_ENCODINGCURLOPT_FOLLOWLOCATION,我想这意味着它是通过http 传输的,其中curl 通常比复制快得多,至少有两个原因:

    1:PHP 的 fopen http 包装器不使用压缩,但是当您在此处将 CURLOPT_ENCODING 设置为空字符串时,您会告诉 curl 尽可能使用压缩。 (虽然这取决于 libcurl 的编译方式,但 gzipdeflate 压缩通常与 libcurl 一起编译。)

    2: copy() 一直从套接字读取,直到远程服务器关闭连接,这可能比文件完全下载时晚得多。同时,curl 只会读取到等于Content-Length:-http 标头的字节,然后关闭连接本身,这通常比在远程服务器关闭连接之前停止 read() 快得多(其中 copy()有,但 curl_exec() 没有。)

    但唯一能确定的方法,TIAS。

    $starttime=microtime(true);
    $ch = curl_init();
    $fp = fopen ($local_file, 'w+');
    $ch = curl_init($remote_file);
    curl_setopt($ch, CURLOPT_TIMEOUT, 50);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_ENCODING, "");
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    echo "used ".(microtime(true)-$starttime)." seconds.\n";
    

    $starttime=microtime(true);
    copy($extFile, "report.csv");
    echo "used ".(microtime(true)-$starttime)." seconds.\n";
    
    • 为您提供大约微秒的精度(IEEE 754 双浮点精度可能会在某种程度上破坏它,但可能还不够重要。)

    【讨论】:

      猜你喜欢
      • 2011-10-29
      • 2011-08-15
      • 1970-01-01
      • 2012-10-26
      • 1970-01-01
      • 2016-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多