php & zip : using class ZipArchive example

Trabla: php & zip : using class ZipArchive example

Solving:

1. Goal - create "lesson_1.zip" with files from folder /var/www/storage/lesson/1/
Directory structure:

/var/www/storage/lesson/1/
/var/www/storage/lesson/1/audio.mp3
/var/www/storage/lesson/1/image.html
/var/www/storage/lesson/1/manifest.xml

Goal:
/var/www/storage/lesson/1/lesson_1.zip

2. Check folder permissions /var/www/storage/lesson/1/ - set 0777

3. Php Code

//Check if class ZipArchive exists
if(!class_exists('ZipArchive')){
   throw new Exception("ZipArchive class not exists", 1);
   die;



$zip = new ZipArchive;

$path = '/var/www/storage/lesson/1/';

$res = $zip->open( $path . 'lesson_1.zip'  , ZipArchive::CREATE);

if(  $res === TRUE ){

    foreach (glob(  $path . '*') as $file_path) { //
  
          // From "/var/www/storage/lesson/1/audio.mp3"  to "audio.mp3" 
          // $zip_file_path - path in zip , if empty - not included in zip 
         // if $zip_file_path = '/a/b/c/audio.mp3' - additional folder structure /a/b/c/ will be created in zip 
          $zip_file_path = str_replace($path ,'', $file_path); //
        
         $result= $zip->addFile( $file_path,  $zip_file_path );

          if( $result  === FALSE ){
      throw new Exception("Error adding file to zip :".$file_path, 1);
  }
   
      }//foreach

      $zip->close();


}else{
     throw new Exception("Error Creating zip. Error Code:".$res, 1);
}

No comments:

Post a Comment