Password Protected Zip File Creation in PHP
Hello readers, today we will learn about a little bit different topics. We will see how we can create a password-protected zip in PHP.
Since a few days back, I’ve been trying to write less theory, just to save time from both sides.
Create A PHP File
Yes, you read it right, we just need a single PHP file to create a password-protected zip file. Let’s see how.
Use the below code :
<?php
$password = 'password'; $zipFileName = 'protected'; $filesToZip = ['test.py', 'test.txt']; shell_exec('zip -jrq -P ' . $password . ' ' . $zipFileName . '.zip ' . 'test.py');
//for multiple files use space between file name shell_exec('zip -jrq -P ' . $password . ' ' . $zipFileName . '.zip ' . 'test.txt test.py');
Code Description
zip
: This is the command-line tool used to create zip archives.-j
: This flag tellszip
to store just the file, not its directory structure. It’s useful if you want to add files from different directories without retaining their original directory structure.-r
: This flag stands for “recursive” and includes all files and directories within the specified directory.-q
: This flag stands for “quiet” and suppresses the output of thezip
command, making the process less verbose.-P
: This flag specifies the password for the zip file.$password
: This is the variable containing the password for the zip file.$zipFileName . '.zip'
: This is the name of the zip file you want to create. The.zip
extension is appended to the variable$zipFileName
.'test.py'
: This is the file or directory you want to add to the zip archive.
So, in summary, the command is creating a zip archive named $zipFileName.zip
(with the password specified by $password
) and adding the file test.py
to it, while ignoring the directory structure (-j
flag) and including all files and directories within test.py
(-r
flag).
Suggested: https://larachamp.com/boost-your-productivity-with-essential-phpstorm-shortcuts/
For Laravel: Creating Password-Protected Zip Files In Laravel
Conclusion
Implementing password protection for zip files in PHP is now simple and secure. Customize the code as needed for dynamic file lists or user authentication.
The post Password Protected Zip File Creation in PHP appeared first on Larachamp.