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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器