PHP生成ZIP压缩文件


PHP生成ZIP压缩文件


/*
 * 生成zip压缩文件
 * $sourceDir:被压缩的文件夹或文件
 * $outFileName:输出的压缩文件名称
 * */
function createZipResources($sourceDir, $outFileName = '', $filesName)
{
    if ($outFileName == '') {
        $outFileName = time().'.zip';
    } else {
        $outFileName = $outFileName.'.zip';
    }

    $fileNames = [];

    //判断需要被压缩的目标是文件还是文件夹
    if (is_file($sourceDir)) {
        $fileNames['file'][basename($sourceDir)] = $sourceDir;
    } else {
        $fileNames = read_all_dir($sourceDir);
    }

    if (!array_key_exists('file', $fileNames) && !array_key_exists('dir', $fileNames)) {
        $fileNames['dir'][basename($sourceDir)] = [];
    }

    // 生成文件
    $zip = new ZipArchive (); // 使用本类,linux需开启zlib,windows需取消php_zip.dll前的注释
    if ($zip->open ($outFileName, ZIPARCHIVE::CREATE ) !== TRUE) {
        exit ( '无法打开文件,或者文件创建失败' );
    }
    $fileNameArr = $fileNames;
    $toFolderZip = function ($fileNameArr, &$zip, $base = '') use (&$toFolderZip) {
        foreach ( $fileNameArr as $key => $value ) {
            if ($key == 'file') {
                foreach ($value as $fileName => $filePath) {
                    $fileName = urldecode($fileName);
                    if ($base == '') {
                        $zip->addFile($filePath, $fileName);
                    } else {
                        $zip->addFile($filePath, $base.'/'.$fileName);
                    }

                }
            }

            if ($key == 'dir') {
                foreach ($value as $folderName => $folderObject) {
                    $folderName = urldecode($folderName);
                    if ($base == '') {
                        $zip->addEmptyDir($folderName);
                        $based = $folderName;
                    } else {
                        $based = $base.'/'.$folderName;
                        $zip->addEmptyDir($based);
                    }
                    $toFolderZip($folderObject, $zip, $based);
                }
            }

        }
    };
    $toFolderZip($fileNameArr, $zip);
    $zip->close(); // 关闭
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header('Content-disposition: attachment; filename='.$filesName.'.zip'); //文件名
    header("Content-Type: application/zip"); //zip格式的
    header("Content-Transfer-Encoding: binary"); //告诉浏览器,这是二进制文件
    header('Content-Length: '. filesize($outFileName)); //告诉浏览器,文件大小
    return @readfile($outFileName);
    //return ['status'=>'YES', 'info' => '压缩完成'];
}

posted @ 2019-01-05 15:02  sfornt  阅读(1233)  评论(0编辑  收藏  举报