doulan4939 2013-08-15 03:44
浏览 261
已采纳

cURL下载二进制文件“双打”文件

We are using cURL to download files from one of our servers to our workflow server. I'm using the simple code pasted below, but my files are "doubling up" - twice the size, twice the length. Would seem the file is saved, then appended again, but I can't figure out why in the world that is happening.

Below is test code on my local machine behaving exact same way:

    $file_name = 'test.mp3';
    $copy_to_dir = 'C:/test_files/';
    $file_url  = 'C:/source_files/test.mp3';

    $fp = fopen ($copy_to_dir. '/' . $file_name, 'w');

    $ch = curl_init($file_url);

    curl_setopt_array($ch, array(
        CURLOPT_URL            => $file_url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FILE           => $fp,
        CURLOPT_TIMEOUT        => 50
    ));

    $results = curl_exec($ch);
    if(curl_exec($ch) === false)
    {
      //echo 'Curl error: ' . curl_error($ch);
        return false;
    }

    curl_close($ch);
    fclose($fp);

Original file is 9MB, copy is 18MB every time

EDIT: let this be a lesson to you not copy/paste code when you're in a hurry, to "save time". The second curl_exec() should be a curl_errno() or other error handling strategy - even just using fwrite() meant I would be downloading everything twice, so you don't want to just quit once you get a workaround

  • 写回答

1条回答 默认 最新

  • doutang6600 2013-08-15 04:22
    关注

    You're calling curl_exec() twice, so it downloads the file twice. Change:

    if(curl_exec($ch) === false)
    

    to:

    if($results === false)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 软件自定义无线电该怎样使用
  • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?
  • ¥15 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)