In this post, I will show you how easily we can unzip a zip file using PHP. I am gonna show you simplest method to extract the zip within the current directory.
In this Application, We have to create a Small application where we can select the file and extract.
First, define the filename into a variable
$zip_filename = "file.zip";
file – File name which is located in the same directory where an application placed.
__DIR__
__DIR__ is a “magic constant” in PHP 5.3 or above which always refers to the current directory of the file from which it is called.
open()
open() is used to opens a file or URL.
extractTo()
extractTo() – Extract the complete archive or the given files to the specified destination.
Complete Code for unzipping the file
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' >
<title>techjunkgigs</title>
<style>
body{
font-family: arial, sans-serif;
word-wrap: break-word;
}
.wrapper{
padding:20px;
line-height: 1.5;
font-size: 1rem;
}
span{
font-family: 'Consolas', 'courier new', monospace;
background: #eee;
padding:2px;
}
</style>
</head>
<body>
<div class="wrapper">
<?php
$zip_filename = "file.zip";
echo "Unzipping <span>" .__DIR__. "/" .$zip_filename. "</span> to <span>" .__DIR__. "</span><br>";
echo "current dir: <span>" . __DIR__ . "</span><br>";
$zip = new ZipArchive;
$res = $zip->open(__DIR__ . '/' .$zip_filename);
if ($res === TRUE) {
$zip->extractTo(__DIR__);
$zip->close();
echo '<p style="color:#00C324;">Extract was successful</p><br>';
} else {
echo '<p style="color:red;">Zip file not found!</p><br>';
}
?>
</div>
</body>
</html>
Images
Above picture shows that the ‘Zip’ file not present in the current directory.
Successfully extracted file 🙂 🙂 🙂
You Can also view
I hope this post helped you to know to Extract the Zip file with PHP. To get the latest news and updates follow us on twitter & facebook, subscribe to our YouTube channel. And If you have any query then please let us know by using the comment form.