Creating a Zip from an array of files in a directory

I am trying to create a Zip file from files that are contained in a folder on my server.

Here's my code:

$zip = new ZipArchive();
$dirArray = array();
$new_zip_file = $temp_unzip_path.'test_new_zip.zip';

$new = $zip->open($new_zip_file, ZIPARCHIVE::CREATE);
if ($new === TRUE) {
    $handle = opendir($temp_unzip_path);
    while (false !== ($entry = readdir($handle))) {
    $dirArray[] = $entry;
    }
    print_r ($dirArray);
    closedir($handle);
} else {
    echo 'Failed to create Zip';
}

$zip->close();

      

I'm really new to PHP, so I'm trying to piece this together from the PHP manual along with some examples I found on the net.

I put it print_r

there temporarily to make sure the entries get added to the array - this is where I plan to add the rest of the zip functionality in the future.

My problem is it doesn't print anything, so I don't know if the files are added to the zip or not.

My code is probably wrong (hopefully not), so if anyone can point me in the right direction, I would be very grateful.

Thank.

+3


source to share


1 answer


I modified your code a bit and it creates a zip file without any problem. If that doesn't work for you, check your directory permissionsmydirectory



<pre><?
$temp_unzip_path = './mydirectory/';
$zip = new ZipArchive();
$dirArray = array();
$new_zip_file = $temp_unzip_path.'test_new_zip.zip';

$new = $zip->open($new_zip_file, ZIPARCHIVE::CREATE);
if ($new === true) {
    $handle = opendir($temp_unzip_path);
    while (false !== ($entry = readdir($handle))) {
        if(!in_array($entry,array('.','..')))
        {
            $dirArray[] = $entry;
            $zip->addFile($temp_unzip_path.$entry,$entry);
        }
    }
    print_r ($dirArray);
    closedir($handle);
} else {
    echo 'Failed to create Zip';
}

$zip->close();
?>

      

+3


source







All Articles