Lets write a very simple php program to upload files and unzip the same in the web server. The program will create a folder with same name as the zip file have then count the number of files and folder in the zip file unzip to the created folder. But it require ZIP Library to enable in the Web Server. Though Zip Library is not enabled by default, ask your server provider to enable Zip Library.

PHP Code

<?php
function recursive_dir($dir) {
foreach(scandir($dir) as $file) {
if ('.' === $file || '..' === $file) continue;
if (is_dir("$dir/$file")) recursive_dir("$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) {
$myMsg = "Please upload a valid .zip file.";
}

/* PHP current path */
$path = dirname(__FILE__).'/'; 
$filenoext = basename ($filename, '.zip'); 
$filenoext = basename ($filenoext, '.ZIP');

$myDir = $path . $filenoext; // target directory
$myFile = $path . $filename; // target zip file

if (is_dir($myDir)) recursive_dir ( $myDir);
mkdir($myDir, 0777);

if(move_uploaded_file($source, $myFile)) {
$zip = new ZipArchive();
$x = $zip->open($myFile); // open the zip file to extract
if ($x === true) {
$zip->extractTo($myDir); // place in the directory with same name
$zip->close();
unlink($myFile);
}
$myMsg = "Your .zip file uploaded and unziped.";
} else { 
$myMsg = "There was a problem with the upload.";
}
}
?>


HTML Code

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Upload and unzip file in webserver</title>
</head> 
<body>
<div class="box">
<div class="heading">Upload File and Unzip</div>
<div class="msg"><?php if($myMsg) echo "<p>$myMsg</p>"; ?></div>
<div class="form_field">
<form enctype="multipart/form-data" method="post" action="">
<label>Upload Zip File: </label> <input type="file" name="zip_file">
<br><br>
<input type="submit" name="submit" value="Upload" class="upload"> <br><br>
</form>
</div>
</div>
</body>
</html>
Download File

Total Downloads: 4553
Top