Trying to get import/export functionality.
- With a folder containing a file
- Zip the folder in PHP using ZipArchive
- Unzip the zipped folder using ZipArchive
-
New folder is created, but the file inside is missing
function unArchive(){ $zip = new ZipArchive; $res = $zip->open('zipTest.zip'); if ($res === TRUE) { echo 'ok'; $zip->extractTo("testfolder2"); $zip->close(); } else { echo 'failed, code:' . $res; } } function Zip($source, $destination){ if (!extension_loaded('zip') || !file_exists($source)){ return false; } $zip = new ZipArchive(); if (!$zip->open($destination, ZIPARCHIVE::CREATE)) { return false; } $source = str_replace('\\', '/', realpath($source)); if (is_dir($source) === true){ $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file){ $file = str_replace('\\', '/', realpath($file)); if (is_dir($file) === true){ $zip->addEmptyDir( str_replace($source . '/', '', $file . '/') ); }else if (is_file($file) === true){ $zip->addFromString( str_replace($source . '/', '', $file), file_get_contents($file)); } } }else if (is_file($source) === true){ $zip->addFromString(basename($source), file_get_contents($source)); } return $zip->close(); } Zip( "testfolder/" , "./zipTest.zip" ); unArchive();
Code works fine for single files. With a file zipped using ZipArchive, I can manually unzip using WinRAR, then rezip using WinRAR, and then ZipArchive can successfully unzip that file. The problem is that ZipArchive won't extract the archive that it directly zipped. I can also see in Notepad++ that the ZipArchive zip is different from the WinRAR zip, and the file size is different. I can successfully call winrar as a system command in php for the desired functionality, but this seems like a bad idea. Is there some reason ZipArchive creates zip files that it can't extract?
Error message: ZipArchive::extractTo(): Invalid argument in [file] on line [$zip->extractTo("testfolder2");]