简体   繁体   English

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

[英]PHP function to download and overwrite the previews downloaded file

I am using the following code to download an archived csv file and uncompress it: 我正在使用以下代码下载存档的csv文件并解压缩:

$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) (CSV文件)

How should I do that? 我该怎么办? The solution should take about the same time as the first download! 该解决方案应与首次下载大致相同的时间!

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;

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM