Home > Article > Backend Development > How to compress files into ZIP file using PHP
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.
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('test.zip') === TRUE) { $zip->addFile('/path/to/index.txt', 'newname.txt'); $zip->close(); echo 'ok'; } else { echo 'failed'; } ?>
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!