Tuesday, July 29, 2014

Handling Zip Archives in PHP - II

In our previous article Handling Zip Archives in PHP - I, we learned about how to create ZIP archive in PHP. In this discussion, we would learn how to extract files from an Archive.

Check out our first code below, this just takes a ZIP Archive and extracts all files and folders from it.

<?php
// First Create a new Object of the class ZipArchive
$archive = new ZipArchive;

// Now OPEN Archive
$result = $archive->open("our_zip.zip");

// Check if the Archive was created successfully
if($result == 1)
{
  // Extract to current Folder
  $archive->extractTo('.');

  // Close the Archive
  $archive->close();
}
else
{
  echo "Archive creation Error [Error code : $result]";
}
?>

The code above is quite self-explanatory. The extractTo() method takes 2 parameters, first being the target folder where it should extract; second parameter is for specifying filenames only which we want to extract from the Archive. We would see an example soon. But before that, check the statement :

$archive->extractTo('.');

The character "." means current folder, ".." means parent folder. However this statement could have been written as shown below ::

<?php
// Extract to Current Working Folder
$archive->extractTo(getcwd());

// Extract to 'test' folder in the current working folder.
//'test' folder will be created if does not exist.
$archive->extractTo("test");  
?>

So, we know how to create an archive and extract files from it. Next we would try to modify the archive.

Here, we are going to rename a file inside the archive. Check out the statement ..

<?php
// This renames test.jpg to tester.jpg within 'images' folder
$zip->renameName('images/test.jpg','images/tester.jpg');
?>

However, we can move a file inside the Archive while renaming. Check the statement below ::

<?php
// This renames test.jpg to tester.jpg within 'images' folder
$zip->renameName('images/test.jpg','tester.jpg');
?>

The above statement move the file 'images/test.jpg' and renames it to 'tester.jpg' and saves it at the root level within the Archive. Similarly we can rename folders and move them accordingly.

Next, let's check out how we can delete files/folders from within a ZIP archive.

<?php
// Delete a file
$archive->deleteName("images/test.jpg");

// Delete a folder
$archive->deleteName("images/");
?>

While deleting a folder, we need to make sure that the name is followed by a "/" character. Secondly, only empty folders can be removed.

To set a comment for the Archive, we need to use setArchiveComment() method.

<?php
// Set the Archive Comment
$archive->setArchiveComment('this is a test comment');

// Get the Archive Comment
$comment = $archive->getArchiveComment();
?>

Next we can read each file within the Archive. Check the statement below ::

<?php
// Read File Content
$file_content = $archive->getFromName('a.txt');

// Print the Content
echo $file_content;
?>

We can get property of individual items within the Archive ::

<?php
// Get file stats
$data = $archive->statName('a.txt');

// Print
print_r($data);
?>

And here is the ourput :: 

Array
(
    [name] => a.txt
    [index] => 9
    [crc] => -1815353990
    [size] => 177045
    [mtime] => 1406113612
    [comp_size] => 378
    [comp_method] => 8
)

It shows that the file size is 177045 bytes which was compressed to 378 bytes.

All files/folders in the Archive has an index number. So, we can delete/rename or get statics of file or do other stuffs with that index number also. Let's check that out. In the example below, we show the list of all the items inside the Archive.

<?php
// LOOP thru files
for ($j = 0; $j < $archive->numFiles; $j++)
{
   // GET filename
   $filename = $archive->getNameIndex($j);
  echo "<br>$filename";
}
?>

Check the Output ::

tester.jpg
images/contact.jpg
images/spinning.gif
images/responsive.png
images/scan0001.jpg
images/test_image.jpg
e.txt
a.txt
b.txt
c.txt
d.txt

See, the code above has listed all the files inside any sub-folders. The ZipArchive object property numFiles (used as $archive->numFiles) holds the total number of files inside the Archive.

Some more functions which take file index number ::

$archive->statIndex(index_number) => Get file statistics
$archive->renameIndex(index_number) => Rename a file
$archive->deleteIndex(index_number) => Delete a file
$archive->getFromIndex(index_number) ==> Get contents of a file

If we want to revert all the changes we did to an item within the Archive, we can use these methods ::

$archive->unchangeName("a.txt");
$archive->unchangeIndex(index_number);

Thursday, July 24, 2014

Handling Zip Archives in PHP - I

Handling ZIP archives, like reading an archive, extracting files from it or putting some files into a ZIP archive etc can be done very easily with PHP. PHP provides the ZipArchive class to create and read zip files. Please make sure that ZIP extension is installed with your version of PHP. So, let's just start with a small piece of code which creates a ZIP archive and put some files in it.

So, here is our first code snippet ... which creates a Zip archive and puts some files into it.

<?php
// First Create Object of the class ZipArchive
$archive = new ZipArchive;

// Now create an Archive 
$result = $archive->open("our_zip.zip", ZipArchive::CREATE);

// Check if the Archive was created successfully
if($result == 1)
{
  // Put a file into it
  $archive->addFile('a.txt', 'apple.txt'); 
  
  // Close the Archive
  $archive->close();
}
else
{
  echo "Archive creation Error [Error code : $result]";
}
?>

So, here is what we did ..

i. Created an object of the ZipArchive class
ii. Called open() method of that class to create our archive
iii. Added a file into the archive by calling addFile() method
iv. And finally we closed the Archive by calling close() method. 

The open() method takes various FLAGs as second argument. These FLAGs are described below.

ZipArchive::CREATE - Create Archive if it does not exist
ZipArchive::OVERWRITE - Overwrite existing Archive
ZipArchive::EXCL - Return error if the Archive already exists. 
ZipArchive::CHECKCONS - Perform additional consistency checks on Archives. Return Error if these checks fail.

If open() method worked perfectly, it returns 1 otherwise various Error codes/FLAGs described below. "ER_" prefix is for errors.

ZipArchive::ER_EXISTS - File exists - 10
ZipArchive::ER_INCONS - Inconsistent Archive - 21
ZipArchive::ER_INVAL  - Invalid arguments - 18 
ZipArchive::ER_MEMORY - Memory allocation failure - 14
ZipArchive::ER_NOENT  - File does not exist - 9 
ZipArchive::ER_NOZIP  - Not a zip archive - 19
ZipArchive::ER_OPEN   - File opening error - 11
ZipArchive::ER_READ   - File reading error - 5
ZipArchive::ER_SEEK   - Seek Error - 4

Let's complicate stuffs a bit more. In our second example, we add a file "b.txt" to the existing Archive "our_zip.zip" but inside a folder 'balloon'.

<?php
// First Create Object of the class ZipArchive
$archive = new ZipArchive;

// Now use existing Archive our_zip.zip
// See that we dont use any FLAG with open() method
$result = $archive->open("our_zip.zip");

// Check if the Archive Open was success
if($result == 1)
{
  // Put a file inside 'balloon' folder
  $archive->addFile('b.txt', 'balloon/balloon.txt'); 
  
  // Close the Archive
  $archive->close();
}
else
{
  echo "Archive creation Error [Error code : $result]";
}
?>

Was not a big deal at all, this piece of code was self-describing... So, now our sample Archive holds the following files ...

apple.txt
balloon/balloon.txt

Let's Add some Content manually to that ZIP archive. We need to use addFromString() method here. See example below..

<?php
// ... create class etc etc

// Build the String
$str = "This is a Sample String, it will be saved in a file called c.txt";

// Write the string as a file c.txt
$archive->addFromString('custom/text/c.txt', 'file content goes here');
?>

The code above would create a file custom/text/c.txt inside that zip archive (in custom/text folder) and write the content of $str variable inside it.

Next, we would browse a folder for some Image files, then put them into a Zip file. This may sometimes come very handy in a situation where a user selects some photos (or PDFs or mixed) on our website and wants them to be downloaded in a zip archive. We would use the ZipArchive class' addGlob() method. 

The scenario :: We have couple of images at the current folder, and we also have some more images in a folder called "test_images". Now, we want to take all the images ( including those in test_images folder ), create a new folder "images" inside the ZIP Archive and put into them. Check out the code below.


<?php
// First Create a new Object of the class ZipArchive
$archive = new ZipArchive;

// Now create an Archive 
$result = $archive->open("our_zip.zip", ZipArchive::OVERWRITE);

// Check if the Archive was created successfully
if($result == 1)
{
  // Set some basic Options for addGlob() method
  $options = array('add_path' => 'images/', 'remove_all_path' => TRUE);
  
  // Now use the Glob() pattern to add all images from current path
  $archive->addGlob('*.{png,jpg,jpeg,gif,bmp}', GLOB_BRACE, $options);
  
  // Add all images under a folder 'test_images'
  $archive->addGlob('test_images/*.{png,jpg,jpeg,gif,bmp}', GLOB_BRACE, $options); 
  
  // Close the Archive
  $archive->close();
}
else
{
  echo "Archive creation Error [Error code : $result]";
}
?>

This code is also very simple. We have used an array $options to create necessary options for the addGlob() method. 

i. 'add_path' => 'images/' means we wanted to create a new path 'images' inside the Archive
ii. 'remove_all_path'=>TRUE means even if we take files from 'folder1' or 'folder2' or 'test_images' ( as found by glob() ), these folder paths will be removed

addGlob() method is taking a pattern as first parameter. Check this statement once again ::

$archive->addGlob('test_images/*.{png,jpg,jpeg,gif,bmp}', GLOB_BRACE, $options); 

GLOB_BRACE flag is used to match any of the extensions provided within the curly braces {}. For more on how Filesystem's glob() function works and glob patterns, check the article Using GLOB in PHP.

We have a ZipArchive method called addEmptyDir() to create empty folders inside the Archive. Check out the statement below :

$archive->addEmptyDir("test_folder");

So, this is actually pretty simple. Check this blog for more on handling ZIP archives in PHP.

In our next article, Handling Zip Archives in PHP - II, we discuss on extracting/renaming/deleting files from the Archive.