Home >Backend Development >PHP Tutorial >How to compress files into ZIP file using PHP

How to compress files into ZIP file using PHP

云罗郡主
云罗郡主Original
2019-01-26 15:30:386052browse

The following php Chinese website introduces how to use PHP to compress files into ZIP files. Through file compression, we reduce the memory of the file, and compress the file and store it on the website.

How to compress files into ZIP file using PHP

One: Use PHP to compress files into ZIP files

When you distribute files by compressing them, you can save the transfer volume, First of all, we need to understand what is a ZIP file?

zip is an archive file format originally created by pkzip developed by pkware company. ZIP files are also often used because data is exchanged through communication functions, allowing data to be compressed.

Two: How to compress to ZIP file

Although it is usually compressed by commands and GUI utilities, PHP also has functions to handle zip files, if using php- m command displays the zip, it will be embedded, the code is as follows:

(PHP 5> = 5.2.0,PHP 7,PECL zip> = 1.1.0)

ZipArchive::addFile - Adds a file to a ZIP archive from the given path

Instructions

ZipArchive :: addFile ( string $filename [, string $localname=NULL [, int $start= 0 [, int $length= 0 ]]]): bool

Add the file Add to the ZIP archive at the given path.

Parameters

filename

The path of the file to be added.

localname

If provided, this is the local name filename that will be overwritten in the ZIP archive.

start

Do not use this parameter, but need to extend ZipArchive.

length

Do not use this parameter, but need to extend ZipArchive.

Return value

Returns TRUE on success, or FALSE on failure.

For example:

<?php
$zip = new ZipArchive;
if ($zip->open(&#39;test.zip&#39;) === TRUE) {
    $zip->addFile(&#39;/path/to/index.txt&#39;, &#39;newname.txt&#39;);
    $zip->close();
    echo &#39;ok&#39;;
} else {
    echo &#39;failed&#39;;
}
?>

Note: For maximum portability, it is recommended to always use forward slashes (/) as directory separators in ZIP file names.

The above is a complete introduction to how to use PHP to compress files into ZIP files. If you want to know more about php tutorial, please pay attention to the php Chinese website.


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

Statement:
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