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 我这模型写的不对吗?为什么lingo解出来的下面影子价格这一溜少一个变量
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波