Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Create ZIP file with PHP
11-22-2009, 04:18 AM
Post: #1
Create ZIP file with PHP
This function creates ZIP archive file using ZipArchive class in 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!');
}
Just change this two lines :
Code:
$my_files = array('File1.txt','File2.txt','File3.txt');
$zip = zipFiles($my_files,'MyZipFile.zip');
Hope you like it !

There's a fine line between genius and insanity. I have erased this line.
Oscar Levant
There's a fine line between an administrator and black hat hacker. I have erased this line.
Dr DEBCOL
Visit this user's website Find all posts by this user
Quote this message in a reply
11-22-2009, 05:04 AM
Post: #2
RE: Create ZIP file with PHP
Nice shit, dawg Smile
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: