ZipArchive is a built-in PHP extension for handling ZIP archives. It supports creating, reading, and updating ZIP files, and also allows you to encrypt and decrypt archives using a password, making it a valuable tool for protecting sensitive data.
To create a password-protected ZIP file using PHP, follow these steps:
Start by creating a new instance of the ZipArchive class. Then use the open() method with the CREATE mode to initialize a new ZIP file. After that, set a password using setPassword().
$zip = new ZipArchive(); $zip->open('encrypted.zip', ZipArchive::CREATE); $zip->setPassword('password');
This snippet creates a ZIP archive named encrypted.zip and sets the password to password.
Once the ZIP file is open and a password is set, use addFile() to include the file you want to compress.
$file = 'example.txt'; $zip->addFile($file);
This example adds example.txt to the ZIP archive.
After adding all desired files, use close() to finalize and save the ZIP archive.
$zip->close();
At this point, you have successfully created an encrypted ZIP file with your chosen contents.
If you need to access the contents of an encrypted ZIP archive, you can decrypt it using ZipArchive as well.
Open the encrypted archive using ZipArchive::READ mode, and then provide the correct password with setPassword().
$zip = new ZipArchive(); $zip->open('encrypted.zip', ZipArchive::READ); $zip->setPassword('password');
Make sure the password matches the one used during the encryption process.
Once the archive is successfully decrypted, extract its contents using the extractTo() method.
$destination = 'extracted/'; $zip->extractTo($destination);
This will extract the files into the specified extracted/ directory.
After extraction, remember to close the archive using close().
$zip->close();
You’ve now successfully decrypted and extracted files from a password-protected ZIP archive.
With PHP's ZipArchive, encrypting and decrypting ZIP files becomes a straightforward process. By using setPassword(), you can protect sensitive data from unauthorized access, and extractTo() allows you to safely retrieve content. These features are especially useful in web applications where file security is a concern. Proper implementation of archive encryption can help enhance the overall security of your project.