Monday, May 23, 2016

Zip File Upploader and Extracting using PHP Script

<?php

if($_FILES["fileToUpload"]["name"]) {
    $file = $_FILES["fileToUpload"];
    $filename = $file["name"];
    $tmp_name = $file["tmp_name"];
    $type = $file["type"];
   
    $name = explode(".", $filename);
    $accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');

    if(in_array($type,$accepted_types)) {
        $okay = true;
    }
   
    $continue = strtolower($name[1]) == 'zip' ? true : false;

    if(!$continue) {
        $message = "The file is not .zip file. Please try again.";
    }


        $ran = $name[0]."-".time()."-".rand(1,time());
        $targetdir = "files/".$ran;
        $targetzip = "files/".$ran.".zip";

    if(move_uploaded_file($tmp_name, $targetzip)) {
     
        $zip = new ZipArchive();
        $x = $zip->open($targetzip);
        if ($x === true) {
            $zip->extractTo($targetdir);
            $zip->close();
   
            unlink($targetzip);
        }
        $message = " <strong>{$ran}.zip</strong> file was uploaded and extracted.";

    } else {  
        $message = "Error!Uploaded file. Please try again.";
    }
}
echo $message;

?>