Home

Tuesday, September 18, 2012

How to Upload and Unpack a Zip File using PHP


<?php
error_reporting(0);
if($_FILES["zip_file"]["name"]) {
 $filename = $_FILES["zip_file"]["name"];
 $source = $_FILES["zip_file"]["tmp_name"];
 $type = $_FILES["zip_file"]["type"];
 
 $name = explode(".", $filename);
 $accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
 foreach($accepted_types as $mime_type) {
  if($mime_type == $type) {
   $okay = true;
   break;
  } 
 }
 
 $continue = strtolower($name[1]) == 'zip' ? true : false;
 if(!$continue) {
  $message = "The file you are trying to upload is not a .zip file. Please try again.";
 }
 
 $target_path = "/home/var/yoursite/httpdocs/".$filename;  // change this to the correct site path
 if(move_uploaded_file($source, $target_path)) {
  $zip = new ZipArchive();
  $x = $zip->open($target_path);
  if ($x === true) {
   $zip->extractTo("/home/var/yoursite/httpdocs/"); // change this to the correct site path
   $zip->close();
 
   unlink($target_path);
  }
  $message = "Your .zip file was uploaded and unpacked.";
 } else { 
  $message = "There was a problem with the upload. Please try again.";
 }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
 
<body>
<?php if($message) echo "<p>$message</p>"; ?>
<form enctype="multipart/form-data" method="post" action="">
<label>Choose a zip file to upload: <input type="file" name="zip_file" /></label>
<br />
<input type="submit" name="submit" value="Upload" />
</form>
</body>
</html>

3 comments:

  1. Hі eveгуone, it's my first pay a quick visit at this web site, and article is genuinely fruitful for me, keep up posting such content.
    my web page - fileserve Captcha bypass

    ReplyDelete
  2. Wow thаt wаs unuѕual. I just wrotе an reallу lοng сommеnt
    but аfter I сliсked submit my comment didn't show up. Grrrr... well I'm
    not writing аll that over agaіn.
    Regaгdless, juѕt wanted to say gгeаt blog!
    my web site - captcha decoder php

    ReplyDelete

rathoddhirendra.blogspot.com-Google pagerank and Worth