PHP ZipArchive打包文件夹压缩下载

针对自己的环境扩展相应版本的php_zip;这里提供一个windows环境下php zip扩展下载地址:https://pecl.php.net/package/zip。

第一步


// 删除文件夹
function delDirFile($path)
{
    $handler = opendir($path); //打开当前文件夹由$path指定。
    if ($handler) {
        while (($filename = readdir($handler)) !== false) {
            if ($filename != "." && $filename != "..") { 
            	//文件夹文件名字为'.'和‘..’,不要对他们进行操作
                if (is_dir($path . "/" . $filename)) { 
                	// 如果读取的某个对象是文件夹,则递归
                    delDirFile($path . "/" . $filename);
                    @rmdir($path . '/' . $filename);
                } else { //删除文件
                    unlink($path . "/" . $filename);
                }
            }
        }
        @closedir($path);
    }
}

// 定义打包文件夹,没有就创建
$needZipPath = './uploads/downloadzip';
if (is_dir($needZipPath)) {
    delDirFile($needZipPath); // 删除文件夹中所有的文件及目录
} else {
    @mkdir($needZipPath, 0755);
}

// 下载文件到打包文件夹中
getYunFile('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1604669815978&di=99bbd74586a18f5a4b19a1893794ed51&imgtype=0&src=http%3A%2F%2Fa1.att.hudong.com%2F05%2F00%2F01300000194285122188000535877.jpg', $needZipPath, '555');

第二步

/**
 * @Note:  下载远程文件保存到本地
 * @param string $url 需要下载的文件url
 * @param string $save_dir 下载下来的文件需要保存到的目录
 * @param string $filename 保存文件名称,当保存文件名称为空时则使用远程文件原来的名称
 * @param int $type 使用的下载方式
 * @return array
 */
function getYunFile($url, $save_dir = '', $filename = '', $type = 0)
{
    $ext = '.' . fileext($url); //以pdf的格式结尾
    clearstatcache(); //清除文件缓存
    //$url = 'http://10.0.0.171:81/uploads/HxqcFreeSingle/201708/2017080918080948257139.pdf';
    if (trim($url) == '') {
        return array('file_name' => '', 'save_path' => '', 'error' => 1);
    }
    if (trim($save_dir) == '') {
        $save_dir = './';
    }
    if (trim($filename) == '') { //保存文件名
        $filename = time();
    }
    if (strpos($filename, ".") === false)
        $filename .= $ext;

    if (0 !== strrpos($save_dir, '/')) {
        $save_dir .= '/';
    }
    //创建保存目录
    if (!is_dir($save_dir)) { //文件夹不存在,则新建
        //print_r($save_dir."文件不存在");
        mkdir(iconv("UTF-8", "GBK", $save_dir), 0777, true);
        //mkdir($save_dir,0777,true);
    }
    //获取远程文件所采用的方法
    if ($type) {
        $ch = curl_init();
        $timeout = 3;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $file = curl_exec($ch);
        curl_close($ch);
    } else {
        ob_start();
        readfile($url);
        $file = ob_get_contents();
        ob_end_clean();
    }
    $size = strlen($file);
    //文件大小
    //var_dump("文件大小:".$size);
    $fp2 = @fopen($save_dir . iconv("UTF-8", "GBK", $filename), 'w');
    fwrite($fp2, $file);
    fclose($fp2);
    unset($file, $url);
    return array('file_name' => $filename, 'save_path' => $save_dir . $filename, 'error' => 0);
}

第三步

// 将打包文件夹中的所有文件添加到zip压缩包中
$zip = new \ZipArchive();
$targetZipFile = './uploads/downloadzip.zip';
if (file_exists($targetZipFile)) {
    // 存在时覆盖
    $zipr = $zip->open($targetZipFile, \ZipArchive::OVERWRITE);
} else {
    // 不存在时创建
    $zipr = $zip->open($targetZipFile, \ZipArchive::CREATE);
}
if ($zipr) {
	//调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法
    addFileToZip($needZipPath . '/', $zip, 'downloadzip/'); 
    $zip->close(); //关闭处理的zip文件
}

/**
 * @Note:  添加文件到zip
 * @param string $path 文件夹路径
 * @param $zip
 */
function addFileToZip($path, $zip, $sub_dir = '')
{
    $handler = opendir($path); //打开当前文件夹由$path指定。
    while (($filename = readdir($handler)) !== false) {
        if ($filename != "." && $filename != "..") { 
        	//文件夹文件名字为'.'和‘..’,不要对他们进行操作
            if (is_dir($path . $filename)) { 
            	// 如果读取的某个对象是文件夹,则递归
                $localPath = $sub_dir . $filename . '/';
                addFileToZip($path . $filename . '/', $zip, $localPath);
            } else { //将文件加入zip对象
                $zip->addFile($path . $filename, $sub_dir . $filename);
            }
        }
    }
    @closedir($handler);
}

第四步

// 输出zip包,下载成功
$fname = $this->param['name'] ?? '';
$file['filename'] = $fname . date('Ymd') . ".zip";

header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename=' . $file['filename']); //文件名
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件
header('Content-Length: ' . filesize($targetZipFile)); //告诉浏览器,文件大小
ob_clean();
flush();
readfile($targetZipFile);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值