How to Upload and Unpack a Zip File using PHP

When you’re emailing or uploading larger files, it always makes sense to compress them first. This decreases file size and also helps avoid file corruption during transfer. The most common compressed file you will encounter is the zip file, since most operating systems come with a basic utility to quickly zip and unzip files. Creating a small function to upload a zip file to your server and unpack in the process isn’t as complicated as you might think.

 

First let’s create a simple form that will allow us to browse our computer and upload a zip file.


<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>

Now comes the uploader function:


<?php 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."; } } ?>

To make sure the success and error messages appear, we will also have to add to short pieces of PHP code:


<?php if($message) echo "<p>$message</p>"; ?>

Putting it all together into a PHP file would look like this:


<?php 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>

Zip File Icon: Ritesh Ranjan

http://bavotasan.com/2010/how-to-upload-zip-file-using-php/

 

PHP – Unzip an uploaded file using php

Published on Sunday, 09 March 2008 22:37

If you dont have shell access to your server and need to unzip a file on your php server you can use the script below:


<?php

     $zip = new ZipArchive;
     $res = $zip->open('my_zip_file.zip');
     if ($res === TRUE) {
         $zip->extractTo('my_extract_to_dir/');
         $zip->close();
         echo 'ok';
     } else {
         echo 'failed';
     }
?> 

Basically it extracts the zip file into the directory you specify… make sure the directory you want to extract it to has write permissions. More info on this script is available on the php website

One issue I ran into with this script was that I could not modify the files via my ftp program as they did not have permission set for this. In my next entry I will show you the chmod script I used to chmod this directory to the needed permissions.

 

http://www.bjw.co.nz/developer/php/62-php-unzip-an-uploaded-file-using-php

 

Script for uploading ZIP file and unzip it on the server

Steps to follow:

  1. create folder on the webserver called "zipper" or something else
  2. copy the following PHP code into a file called "zipper.php" into this folder
  3. use the url to this file to start the little script
  4. select a zip file from your harddisk and go for it
  5. after upload a directory exists in the folder "zipper" from step 1
  6. with ftp program (like Filezilla) you can easily move the content to the directory of your choice (that’s all)

<?php
/* Simple script to upload a zip file to the webserver and have it unzipped
  Saves tons of time, think only of uploading WordPress to the server
  Thanks to c.bavota (www.bavotasan.com)
  I have modified the script a little to make it more convenient
  Modified by: Johan van de Merwe (12.02.2013)
*/

function rmdir_recursive($dir) {
    foreach (scandir($dir) as $file) {
        if ('.' === $file || '..' === $file)
            continue;
        if (is_dir("$dir/$file"))
            rmdir_recursive("$dir/$file");
        else
            unlink("$dir/$file");
    }
    rmdir($dir);
}

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.";
    }

    /* PHP current path */
    $path = dirname(__FILE__) . '/';  // absolute path to the directory where zipper.php is in
    $filenoext = basename($filename, '.zip');  // absolute path to the directory where zipper.php is in (lowercase)
    $filenoext = basename($filenoext, '.ZIP');  // absolute path to the directory where zipper.php is in (when uppercase)

    $targetdir = $path . $filenoext; // target directory
    $targetzip = $path . $filename; // target zip file

    /* create directory if not exists', otherwise overwrite */
    /* target directory is same as filename without extension */

    if (is_dir($targetdir))
        rmdir_recursive($targetdir);
    mkdir($targetdir, 0777);

    /* here it is really happening */

    if (move_uploaded_file($source, $targetzip)) {
        $zip = new ZipArchive();
        $x = $zip->open($targetzip);  // open the zip file to extract
        if ($x === true) {
            $zip->extractTo($targetdir); // place in the directory with same name 
            $zip->close();

            unlink($targetzip);
        }
        $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>Unzip a zip file to the webserver</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>

http://tipila.com/tips/129/script-for-uploading-zip-file-and-unzip-it-on-the-server

Leave a comment