How to Create, Extract Zip and Delete Files or Folders from Zip In Laravel
In this article, I’m going to share an easy method to zip & unzip in Laravel. I’m testing in Laravel 6.2. Let’s get started:
Table of Contents
Install Package
We’ll use zanysoft/laravel-zip package. Install the package using this command:
composer require zanysoft/laravel-zip
Create Zip
We’re able to create zip using this package. I’m showing a few exmaples.
use ZanySoft\Zip\Zip;
$zip = Zip::create('file.zip'); // create zip
$zip->add(public_path()); // add public path to the zip file
We can also add more files/folders to the zip file like these:
$zip->add('/path/to/my/file');
// declaring path
$zip->setPath('/path/to/my')->add('file');
// add directory
$zip->add('/path/to/my/directory');
// add directory (only its content)
$zip->add('/path/to/my/directory', true);
We can also add multiple files/directories to zip:
// using array as parameter
$zip->add( array('/path/to/my/file1', '/path/to/my/file2');
// chaining methods
$zip->add('/path/to/my/file1')->add('/path/to/my/file2');
// declaring path
$zip->setPath('/path/to/my')->add('file1')->add('file2');
Extract Zip
We can easily unzip any zip file. Have a look at the example:
$zip = Zip::open('file.zip');
$zip->extract(public_path() . '/uncompressed');
We can also unzip multiple multiple files too. Here are some examples:
// extract whole archive
$zip->extract('/path/to/uncompressed/files');
// extract a file
$zip->extract('/path/to/uncompressed/files', 'file');
// extract multiple files
$zip->extract('/path/to/uncompressed/files', array('file1','file2'));
Delete Files/Folders from Zip
By using this package we’re able to delete files/folders from the compressed zip file. Take a look at the example:
$zip = Zip::open('file.zip');
$zip->delete('public/robots.txt');
We can also delete multiple files/directories from zip:
// using array as parameter
$zip->delete( array('file1', 'file2') );
// chaining methods
$zip->delete('file1')->delete('file2');
Basic Operations
Here are some of functionalities of the package:
Check zip file:
$is_valid = Zip::check('file.zip');
List content of zip file:
$zip->listFiles();
Use password for zip extraction:
// set password
$zip->setPassword('your-password');
// get password
$password = $zip->getPassword();
Close zip file:
$zip->close();
There are more additional functionalities. Please check these from GitHub.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.