Check if ZIP file is valid with PHP

November 18th, 2011 by Alex Leave a reply »

Recently, i tried to check if ZIP file is valid by checking its MIME type. But server to server, it varies and sometimes even shows up like application/unknown. This is bad, so let’s just rely on native PHP functions:

function zipIsValid($path) {
  $zip = zip_open($path);
  if (is_resource($zip)) {
    // it's ok
    zip_close($zip); // always close handle if you were just checking
    return true;
  } else {
    return false;
  }
}
 
if (zipIsValid('myzip.zip')) {
  // do stuff
  // ...
}

zip_open will return a resource in case of successful opening, otherwise it will return an integer with error code, so checking for if ($zip) won’t be proper.


Comments are closed.