Search code examples
phpserverunzip

Unzip a zip archive on a server with php


I've tryed some ways to automatically unzip files with php but all of them failed:

1st variant

<?php
function unzip($file){
  $zip=zip_open(realpath(".")."/".$file);
  if(!$zip) {return("Unable to proccess file '{$file}'");}
  $e='';

  while($zip_entry=zip_read($zip)) {
   $zdir=dirname(zip_entry_name($zip_entry));
   $zname=zip_entry_name($zip_entry);

   if(!zip_entry_open($zip,$zip_entry,"r")) {$e.="Unable to proccess file '{$zname}'"; continue; }
   if(!is_dir($zdir)) mkdirr($zdir,0777);

   #print "{$zdir} | {$zname} \n";

   $zip_fs=zip_entry_filesize($zip_entry);
   if(empty($zip_fs)) continue;

   $zz=zip_entry_read($zip_entry,$zip_fs);

   $z=fopen($zname,"w");
   fwrite($z,$zz);
   fclose($z);
   zip_entry_close($zip_entry);

   } 
zip_close($zip);

return $e;
} 
$file = 'file_name.zip';
echo unzip($file);

2nd variant

<?php
$zip = zip_open("my_linkedin_groups_scrape_my_run_1_2015.zip");
if ($zip) {
while ($zip_entry = zip_read($zip)) {
  $fp = fopen("./".zip_entry_name($zip_entry), "w");
  if (zip_entry_open($zip, $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($zip);
}
?>

3rd variant

<?php 
// assuming file.zip is in the same directory as the executing script.
$file = 'file.zip';

// get the absolute path to $file
$path = pathinfo(realpath($file), PATHINFO_DIRNAME);

$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
  // extract it to the path we determined above
  $zip->extractTo($path);
  $zip->close();
  echo "WOOT! $file extracted to $path";
} else {
  echo "Doh! I couldn't open $file";
}
?>

for the 3rd case output is Doh! I couldn't open file.zip

What's wrong? Am I something missing? I


Solution

  • Seems like a problem with write/read rights.
    Change the rights for testing purposes on to 0777