PHP – Extracting a zip compressed archive into a folder

Below code sample is for extracting the contents of a .zip file into a folder given by ‘/test/’. Note that if the folder ‘test’ is not there, it is created.

$zip = new ZipArchive;
if ($zip->open($outFile) === TRUE) {
    $zip->extractTo('/test/');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}

The method extractTo does the process of reading all files and filenames in the archive and writing new equivalent files in the output folder. We can also selectively extract files.. for examples we want to modify the above example such that only testFile2.txt and testFile4.txt is extracted.

$zip->extractTo('/test/',array('testFile2.txt','testFile4.txt'));

Leave a Reply

Your email address will not be published. Required fields are marked *

*