How to zip file in PHP?

by dalton_moen , in category: PHP General , 9 months ago

How to zip file in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , 3 months ago

@dalton_moen 

You can use the ZipArchive class in PHP to create a zip file. Here is an example of how to create a zip file and add a file to it:

1
2
3
4
$zip = new ZipArchive;
$zip->open('file.zip', ZipArchive::CREATE);
$zip->addFile('file.txt');
$zip->close();


This example creates a new ZipArchive object, opens a zip file called "file.zip" for writing, adds the file "file.txt" to the zip file, and then closes the zip file.


You can also add multiple files to the zip file by calling the addFile method multiple times, or you can add an entire directory to the zip file using the addDir method.


For more information about the ZipArchive class and its methods, you can refer to the PHP documentation: https://www.php.net/manual/en/class.ziparchive.php