Tags
PHP , zip
Asked 7 years ago
29 Dec 2016
Views 592

posted

how to do zip in php

how to do zip in php, one file or multiple file to zip by php.
debugger

debugger
answered Apr 24 '23 00:00

Zip is a popular file format used for compressing and archiving files. In PHP, you can use the built-in ZipArchive class to create and extract zip archives. Here's an example of how to create a zip archive using PHP:



// Create a new ZipArchive object
$zip = new ZipArchive();
$zipname = 'example.zip';

// Open the zip archive for writing
if ($zip->open($zipname, ZipArchive::CREATE) !== TRUE) {
    die('Could not open archive');
}

// Add files to the zip archive
$zip->addFile('file1.txt');
$zip->addFile('file2.txt');

// Close the zip archive
$zip->close();

// Download the zip archive
header('Content-Type: application/zip');
header("Content-Disposition: attachment; filename=$zipname");
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

This code snippet creates a new ZipArchive object, opens the zip archive for writing using the open() method, adds files to the zip archive using the addFile () method, closes the zip archive using the close () method, and then downloads the zip archive using the appropriate headers and readfile () function.

Note that the php-zip extension needs to be installed on the server to use the ZipArchive class.
Post Answer