Extract zip file in PHP

0
3
Extract zip file in PHP
Extract zip file in PHP

Maybe you want to know how to decompress zip file in PHP? I will show you how to extract zip file in PHP in this article.

To decompress zip archive in PHP, we will use ZipArchive class.

It will take four steps to extract a zip archive:

  1. Create an instance of ZipArchive.
  2. Open an output writer for zip archive.
  3. Decompress zip archive.
  4. Finalize the operation.

Following is the complete code demonstrates how to extract zip file in PHP:

$file = 'compressed.zip';
$extractDirectory = dirname(__FILE__) . '/extracted/';

// Step 1: create an instance
$zip = new ZipArchive();

// Step 2: try to open zip archive
$status = $zip->open($file);
if ($status === TRUE) {
    // Step 3: decompress zip archive
    $zip->extractTo($extractDirectory);

    // Step 4: finalize the operation
    $zip->close();

    echo "Zip file $file has been extracted into $extractDirectory\n";
} else {
    echo "Failed to extract $file\n";
}

That’s it!