Unzip file with php code

UNZIP FILE WITH PHP CODE
In this tutorial we are going to learn how PHP unzip a package.
Here is the code which i am using to unzip package in same folder where package uploaded.
$zipfile = 'package.zip'; $unzip = new ZipArchive; $out = $unzip->open($zipfile); if ($out === TRUE) { $unzip->extractTo(getcwd()); $unzip->close(); echo 'File unzipped'; } else { echo 'Error'; } }
Lets discuss the parts of code.
$zipfile = ‘package.zip’; ( This is variable mentioned name of the package , Eg: if your package.zip is wordpress.zip then write wordpress.zip instead of package.zip )
$unzip = new ZipArchive; (ZipArchive is function of PHP core which used to Unzip or Zip files and folders )
$out = $unzip->open($zipfile); ( This is the code which will check if the zipfile is really good zip and able to unzip )
if ($out === TRUE) ( This is to for the $out result either True or False , if file is able to unzip then it will return TRUE other wise FALSE )
$unzip->extractTo(getcwd()); ( extractTo is the function which is called on $unzip to proceed the task. getcwd() is the function to find the present directory where zip file is uploaded )
$unzip->close(); ( This is a good practice to close the functions which we are using so that it will relax the thread using it in PHP )
It is a working code which i am using for my FTP packages.
I modified this code with a calling variable so that i can directly type zip file on URL and extract it , this helps me not to edit unzip.php file every time i upload a package.
Here is the code i am using for myself
if(!empty($_GET) AND isset($_GET['v'])) { $zipfile = trim($_GET['v']); $unzip = new ZipArchive; $out = $unzip->open($zipfile); if ($out === TRUE) { $unzip->extractTo(getcwd()); $unzip->close(); echo 'File unzipped'; } else { echo 'Error'; } } else { echo "No Zip File Mentioned"; }
Here $_GET[‘v’] using to put anything.zip in url directly and extract it. For example : I uploaded myscript.zip in my FTP folder so i will directly write https://mydomain.com/foldername/unzip.php?v=myscript.zip and hit the enter button and inside foldername my package will get unzipped. This helps me not to edit unzip.php every time i upload any name .zip file.
I hope this tutorial helps readers to solve their issues.
Are you interested in more PHP Tutorials ?
1 thought on “Unzip file with php code”