Skip to content


Creating Zip Files in PHP

This sections will contains code regarding different PHP & MySQL features and contains help about php/mysql issues.

Creating Zip Files in PHP

Postby php developer » April 3rd, 2009, 10:54 am

Creation of a Zip Archive in PHP is not a difficult task, it is very easy to manipulate Zip Files using the PHP Zip extension. Here is a simple php code to create a new zip file.

Code: Select all
   $objZip   = new ZipArchive( );
   $sZipFile = "demo.zip";

   if ($objZip->open($sZipFile, ZIPARCHIVE::CREATE) === TRUE)
   {
      $objZip->addFile("/path/file-a.ext", "file-a.ext");
      $objZip->addFile("/path/file-b.ext", "file-b.ext");
      $objZip->close( );
   }


First of all, we are creating a new zip archive using the code
Code: Select all
    $objZip   = new ZipArchive( );

    $objZip->open($sZipFile, ZIPARCHIVE::CREATE);


Then we have to add files into the archive using the addFile function.
Code: Select all
      $objZip->addFile("/path/file-a.ext", "file-a.ext");


And in the end, we are closing the zip archive creation process.
Code: Select all
      $objZip->close( );
User avatar
php developer
 
Posts: 53
Joined: July 25th, 2008, 4:56 am


Unzipping Zip Files in PHP

Postby Shahzad Butt » April 24th, 2009, 5:33 am

Unzipping/Extracting a zip file in PHP is also very simple. The following code shows a basic example of unzipping of a zip file.

Code: Select all
      // Extracting the zip file
      $objZip = new ZipArchive( );

                $sZipFile = "sample.zip";

      if ($objZip->open($ZipFile) === TRUE)
      {
         $objZip->extractTo("sample/");
         $objZip->close( );
      }


The above code assumes that you have a sample.zip file, and you are extracting this into the folder named "sample" within the directory where you are running this script.
Regards
Shahzad Butt
User avatar
Shahzad Butt
 
Posts: 32
Joined: July 9th, 2008, 11:16 am
Location: Pakistan


Return to Board index

Return to PHP / MySQL / XML

Who is online

Users browsing this forum: No registered users and 0 guests