duancongjue9202 2013-08-02 09: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 09: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;
    

    }

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部