Create and Extract A ZIP Archive

Posted by Pete | Posted in PHP Tutorials | Posted on 10-08-2009-05-2008

0

ZIP’s are used for on both Linux and Windows Operating Systems. They can be used for compressing files and storing multiple files in one location. In this tutorial I will show you how to create and extract a ZIP Archive using PHP.

So lets get started. First I will show you how to create the ZIP Archive.

To begin first we must create some files which will go into the ZIP. For this tutorial I will use a directory and 2 files these are /zipfiles/index.html and /putinarchive.txt

open($name_of_zip, ZipArchive::CREATE); // Try create the archive.
if ($open === TRUE) { // If it was created carry on.
    $zip->addFromString('newfile.txt', 'This file has been created via PHP and will be put into the ZIP.'); // This will add a file to the archive but it wont exist on locally until extracted.
    // AddFile structure - addFile('File Location To Be Added','Local Name In Archive.');
    $zip->addFile('putinarchive.txt', 'putinarchive.txt'); // Put in a file that exists into the ZIP Archive.
    $zip->addFile('zipfiles/', 'zipfiles/'); // Add zipfiles/ directory to the zip archive
    $zip->close(); // Close the archive
    echo 'ok'; // Say it was ok.
} else {
    echo 'failed'; // If it didn't create it echo failed.
}
?>

So that is how to add the files to the archive in the archive you should now have 3 files and 1 directory. So lets get onto how to extract the stuff out of it.

open($name_of_zip); // Open and read the zip file.
if ($res === TRUE) { // If it can read it carry on.
    $zip->extractTo('archivefiles/'); // Extract the files to archivefiles/ directory
    $zip->close(); // Close the zip archive
    echo 'ok'; // Echo OK
} else { // If it couldnt read it
    echo 'failed, code:' . $res; // Echo failed and the error.
}
?>

So thats it. One problem you may come across is that you may not be able to do this. This could be because your host has to enable ZIP when rebuilding PHP. So if you have used my examples and still cant do it ask your host to check if ZIP is built with PHP. If you have any further questions please leave a comment and Id love any feedback.

Write a comment

You must be logged in to post a comment.

Tutorials Written By Peter Kelly