How to upload zip file using php

INTRODUCTION

We will see how can we upload zip file to the server using PHP step by step.

This is form for the uploading the zip file

[uploadzip.html]

<form enctype=”multipart/form-data” method=”post” action=”uploadZipFile.php”>

<label>Choose a zip file to upload: </label><input type=”file”  name=”zip_file” required/>

<input  type=”submit” name=”submit” value=”Upload Zip” />

 

[uploadZipFile.php]

<?php

if(isset($_POST[‘submit’])){

if($_FILES[“zip_file”][“name”]) {

$filename = $_FILES[“zip_file”][“name”];       //file name for the zip file

$source = $_FILES[“zip_file”][“tmp_name”]; // source path of the zip file

$type = $_FILES[“zip_file”][“type”];   // store type of file

$name = explode(“.”, $filename);    // it will break the zip file name in two part

$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) {

echo “File you are trying to upload not Zip file please upload Zip file”;

break;

}

$target_path1 = “media/bluethink/image/”.$filename; // path where zip file will upload and extract

if(move_uploaded_file($source, $target_path1)) {

$zip = new ZipArchive();

$x = $zip->open($target_path1);

if ($x === true) {

$zip->extractTo(“media/bluethink/image”); // change this to the correct site path

$zip->close();

unlink($target_path1); // it will delete zip file after extracting it.

}

echo “Zip file uploaded successfully and extracted.”;

} else {

echo “There is problem in uploading zip file. Please Try again.”;

}

}

}

}

?>