Current Location: Home> Latest Articles> How to Encrypt and Decrypt ZIP Files Using PHP ZipArchive

How to Encrypt and Decrypt ZIP Files Using PHP ZipArchive

gitbox 2025-07-17

Introduction

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.

Create an Encrypted ZIP Archive

To create a password-protected ZIP file using PHP, follow these steps:

Open a ZIP File and Set a Password

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.

Add Files to the Archive

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.

Close the 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.

Decrypting an Encrypted ZIP Archive

If you need to access the contents of an encrypted ZIP archive, you can decrypt it using ZipArchive as well.

Open the ZIP File and Provide the Password

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.

Extract Files from the Archive

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.

Close the Archive

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.

Conclusion

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.