How to compress files in php

爱喝马黛茶的安东尼
Release: 2023-02-25 15:56:01
Original
4205 people have browsed it

How to compress files in php

Compress a file

We generate a compressed package from a file.

open($filename,ZipArchive::CREATE);   //打开压缩包
$zip->addFile($path,basename($path));   //向压缩包中添加文件
$zip->close();  //关闭压缩包
Copy after login

The above code compresses the c:/wamp/www/log.txt file into test.zip and saves it in the current directory.

Related recommendations: "php Getting Started Tutorial"

Compress multiple files

Compressing multiple files is actually addFile Execution multiple times can be achieved by traversing the array.

open($filename,ZipArchive::CREATE);   //打开压缩包
foreach($fileList as $file){
    $zip->addFile($file,basename($file));   //向压缩包中添加文件
}
$zip->close();  //关闭压缩包
Copy after login

Compress a directory

addFile($path."/".$filename);
            }
        }
    }
    @closedir($path);
}
$zip=new ZipArchive();
if($zip->open('rsa.zip', ZipArchive::OVERWRITE)=== TRUE){
    addFileToZip('rsa/', $zip); //调用方法,对要打包的根目录进行操作,并将ZipArchive的对象传递给方法
    $zip->close(); //关闭处理的zip文件
}
Copy after login

Compress and download the zip package

In my case, we need to provide it after packaging Download and then delete the compressed package.

can be divided into the following steps:

(1) Determine whether the given path is a folder or a file. The folder also needs to be traversed to add files.

(2) Set the relevant file header and use the readfile function to provide downloading.

(3) Use the unlink function to delete the compressed package.

addFile($path."/".$filename);
            }
        }
    }
    @closedir($path);
}
$zip=new ZipArchive();
if($zip->open('rsa.zip', ZipArchive::OVERWRITE)=== TRUE){
    $path = 'rsa/';
    if(is_dir($path)){  //给出文件夹,打包文件夹
        addFileToZip($path, $zip);
    }else if(is_array($path)){  //以数组形式给出文件路径
        foreach($path as $file){
            $zip->addFile($file);
        }
    }else{      //只给出一个文件
        $zip->addFile($path);
    }
    $zip->close(); //关闭处理的zip文件
}
Copy after login

The above is the detailed content of How to compress files in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!