Zipping a folder with PHP

APD Toronto
APD Toronto used Ask the Experts™
on
Hi Experts,

How can I create a .zip file from a folder, using PHP?

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Mark BradyPrincipal Data Engineer

Commented:
Here is a script on StackOverflow showing how to zip a whole folder in PHP. Enjoy

Zip a Folder with PHP
Most Valuable Expert 2011
Top Expert 2016
Commented:
This seemed to work OK for me.
<?php // demo/zip_archive.php

/**
 * Create a Zip Archive from a subdirectory
 *
 * http://php.net/manual/en/zip.examples.php
 * http://php.net/manual/en/zip.examples.php#85714 <-- Errors are obscure!
 * http://php.net/manual/en/class.ziparchive.php
 * http://php.net/manual/en/ziparchive.close.php#101606
 */
error_reporting(E_ALL);
date_default_timezone_set('America/New_York');


// THIS IS THE LIST OF scandir() RESPONSES THAT WE DO NOT WANT
$unwanted
= array
( '.'
, '..'
, 'teste2.txt'
)
;


// THE URL ARGUMENT IS THE NAME OF THE DIRECTORY TO ZIP
$dir = (!empty($_GET["dir"])) ? $_GET["dir"] : NULL;

// BUT FOR MY TESTS IT IS HARDCODED
$dir = 'oop5';
if (!$dir) die("PLEASE PROVIDE dir= IN THE URL");


// A GOOD PATH ON MY SERVER
$path
= getcwd()
. DIRECTORY_SEPARATOR
. $dir
;
if (!is_dir($path)) die("FAIL: NOT VALID PATH $path");


// INSTANTIATE THE OBJECT
$zip = new ZipArchive();

// CREATE A DATE-TIME ARCHIVE NAME
$archive
= date('Ymd\THis')
. '_archive_'
. $dir
. '.zip'
;
// TRY TO CREATE THE ARCHIVE
if ($zip->open($archive, ZIPARCHIVE::CREATE) !== TRUE) trigger_error("FAIL: ZIP->OPEN $archive", E_USER_ERROR);


// GET THE LIST OF FILES
if (!$files = scandir($path)) die("FAIL: scandir() $path");
foreach ($files as $file)
{
    $filename = $path . DIRECTORY_SEPARATOR . $file;

    // SKIP THE UNWANTED AND ADD THE OTHERS TO THE ARCHIVE
    if ( in_array($file, $unwanted) ) continue;
    if ( !is_file($filename) )        continue;
    // ACTIVATE THIS FOR A PROGRESS REPORT: echo PHP_EOL . "$filename: $file";
    $zip->addFile($filename, $file );
}

if (!$zip->close()) die("FAIL: ZIP->CLOSE");

$fs  = filesize($archive);
$fsn = number_format($fs);


// PREPARE A LINK
$link
= '<a target="_blank" href="'
. $archive
. '">'
. "DOWNLOAD $archive $fsn BYTES"
. '</a>'
;
echo PHP_EOL . $link;

/**
 * You can use something like this to send the Zip Archive directly to the browser
 *
header("Content-Type: archive/zip");
header("Content-Disposition: attachment; filename=$dir".".zip");
header("Content-Length: $fs");
readfile($archive);
 */

Open in new window

APD TorontoSoftware Developer

Author

Commented:
Thanks Ray!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial