duancongjue9202 2013-08-02 17:36
浏览 52
已采纳

PHP函数下载并覆盖预览下载文件

I am using the following code to download an archived csv file and uncompress it:

$url="http://www.some.zip";
$target = 'data-' . md5(microtime()) . '.zip';

function download($src, $dst) {
        $f = fopen($src, 'rb');
        $o = fopen($dst, 'wb');
        while (!feof($f)) {
            if (fwrite($o, fread($f, 2048)) === FALSE) {
                   return 1;
            }
        }
        fclose($f);
        fclose($o);
        return 0;
}

download($url,$target);

if ( file_exists($target) ){
    echo "Download Successuful <br />";
    $arc = new ZipArchive;
    if (true !== $arc->open($target)) {
        echo "Unzipping Failed <br />";
    }else {
        file_put_contents($out, $arc->getFromIndex(0));
        echo "Unzipping Successuful <br />";
        fclose($handle);
    }
}else {
     echo "Download Failed <br />";
}

However, on a second run, it does't do anything and I would like to overwrite the initial file with the newer file. (the CSV File)

How should I do that? The solution should take about the same time as the first download!

  • 写回答

1条回答 默认 最新

  • douzhongjian0752 2013-08-02 17:45
    关注

    The easiest solution would be to first check if the file exists, then remove it.

    function download($src, $dst) {
        if(file_exists($dst)) unlink($dst);
        $f = fopen($src, 'rb');
        $o = fopen($dst, 'wb');
        while (!feof($f)) {
            if (fwrite($o, fread($f, 2048)) === FALSE) {
                   return 1;
            }
        }
        fclose($f);
        fclose($o);
        return 0;
    

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大