Search code examples
phpzipcodephp-ziparchive

How to Zip the image file and extract it using PHP? My code yields corrupt extraction


i have a form in which user can upload 100 mb file which results delay in upload, hence I decided to first zip the image on form submit and then upload it on server and then extract it on server. so that loading process decreases, Hence for this I have used a script which is as follows:

<?php
$zip = new ZipArchive();
$filename = "newzip.zip";

if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
   exit("cannot open <$filename>\n");
}
$zip->addFromString("myfile.jpeg", 
"This is the first file in our ZIP, added as 
firstfile.txt.\n");

echo "numfiles: " . $zip->numFiles . "\n";
$zip->close();

$zip1 = zip_open("newzip.zip");
if ($zip1) {
  while ($zip_entry = zip_read($zip1)) {
    $fp = fopen(zip_entry_name($zip_entry), "w");
    if (zip_entry_open($zip1, $zip_entry, "r")) {
      $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
      fwrite($fp,"$buf");
      zip_entry_close($zip_entry);
      fclose($fp);
    }
  }
  zip_close($zip1);
  unlink("newzip.zip");
}
?>

Now here from the above code I get the image extracted, but after extraction the size of image is reduced to 61 bytes and is corrupt i.e. it cannot be viewed.

What could be wrong with this code please guide me


Solution

  • I think you are confusing client-side and server-side here. You simply can't create a ZIP clientside, since the PHP script is executed on the server side. So you either have to instruct your users to zip the files before submitting them, or use ie. a Java applet to zip the file for them before uploading.