Support Forums

Full Version: Create a Zip File using PHP
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Credits and Source: http://www.dreamincode.net/

Name: Create a zip file in PHP
Description: This is a snippet for creating a zip file with PHP using the ZipArchive class
Snippet:
PHP Code:
function zip_files($files_to_add = array(), $save_to ''$overwrite_existing false)
{
    
//if the file already exists and overwrite is
    //set to false then return false and get out
    
if(file_exists($save_to) && !$overwrite_existing)
    {
        return 
false;
    }
    
    
//now on to the action
    
$files = array();
    
    
//check for an array
    
if(is_array($files_to_add))
    {
        
//loop through each file in the array
        
foreach($files_to_add as $valid_file)
        {
            
//if the file exists then add to the file array
            
if(file_exists($valid_file))
            {
                
$files[] = $valid_file
            
}
            
            
//check the count of files
            
if(count($files))
            {
                
//create a new zip archive object
                
$zip_archive = new ZipArchive();
                
                
//open zip archive for modifying and check for a value
                //of true with the modes specified
                
if($zip_archive->open($save_to$overwrite_existing ZIPARCHIVE::OVERWRITE ZIPARCHIVE::CREATE) != true)
                {
                    return 
false;
                }
                
                
//loop through the file array
                //adding each file to the new zip archive
                
foreach($files as $file)
                {
                    
$zip_archive->addFile($file$valid_file);
                }
                
                
//close the zip archive
                
$zip_archive->close();
                
                
//finally make sure the new zip file exists
                
return((file_exists($save_to)) ? true false);
            }
        }
    }
}

//Example usage

$my_files = array('File1.txt','File2.txt','File3.txt');

$zip zipFiles($my_files,'MyZipFile.zip');

if(!
$zip)
{
    echo(
'There was a problem creating the zip file');
}
else
{
    echo(
'Zip file created!');


Instructions: Requirements:

PHP 4:
The bundled PHP 4 version requires » ZZIPlib, by Guido Draheim, version 0.10.6 or later

PHP 5.2.0 or later:
This extension uses the functions of » zlib by Jean-loup Gailly and Mark Adler.

Thankyou for reading. Be happy always Smile