How to unzip a file using PHP ?

To unzip a file using PHP, the ZipArchive class provides a straightforward solution. This built-in class allows you to manage zip files without requiring additional plugins. With ZipArchive, you can easily create or extract zip files in PHP. The extractTo() method is particularly useful for extracting the contents of a zip file to a specified directory.

Syntax:

bool ZipArchive::extractTo( string $destination, mixed $entries )

$destination: Defines the directory path where files will be extracted.
$entries: Specifies the file(s) to extract. You can pass a single file or an array of files.

Example:

<?php
$zip = new ZipArchive;
if ($zip->open('example.zip') === TRUE) {
    $zip->extractTo('/Destination/Directory/');
    $zip->close();
    echo 'Unzipped Successfully!';
} else {
    echo 'Unzipped Failed!';
}
?>

In this example, an object of the ZipArchive class is created, and the open() method checks if the zip file can be opened. If successful, the extractTo() method extracts all files to the specified directory.

Example 2: Extract Specific Files

<?php
$zip = new ZipArchive;
if ($zip->open('example.zip') === TRUE) {
    $zip->extractTo('/Destination/Directory/', ['file1.txt', 'image.png']);
    $zip->close();
    echo 'Specific Files Unzipped Successfully!';
} else {
    echo 'Unzipped Failed!';
}
?>

Here, only specified files are extracted from the zip archive using the extractTo() method with an array of filenames.

This method is efficient and ideal for managing zip files in PHP, making file extraction simple and hassle-free.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *