The ZipArchive class in PHP is used for creating and manipulating ZIP files. Although ZipArchive does not directly support encryption, combined with the openssl extension, we can implement encryption and decryption for ZIP archives to enhance file security.
Make sure the PHP environment has both ZipArchive and openssl extensions enabled. You can enable them by uncommenting extension=zip and extension=openssl in your php.ini configuration.
First, create a ZIP archive using ZipArchive and add the target files to it. Then, encrypt the contents of the ZIP file using openssl encryption functions. Below is a sample code snippet:
<?php
$zip = new ZipArchive();
$zipname = 'encrypted.zip';
if ($zip->open($zipname, ZipArchive::CREATE) === TRUE) {
// Add file to archive
$zip->addFile('data.txt', 'data.txt');
$zip->close();
// Read ZIP data and encrypt
$zipdata = file_get_contents($zipname);
$encryptedzip = openssl_encrypt($zipdata, 'AES-128-CBC', 'password', OPENSSL_RAW_DATA, '1234567890123456');
file_put_contents($zipname, $encryptedzip);
echo 'ZIP archive has been encrypted.';
} else {
echo 'Failed to create ZIP archive.';
}
?>
This example uses AES-128-CBC encryption with the password password and initialization vector 1234567890123456. You can customize the encryption algorithm and key as needed.
To decrypt, use openssl's decryption function to restore the original ZIP file, then extract it with ZipArchive. Here is a sample code snippet:
<?php
$zipname = 'encrypted.zip';
// Read the encrypted ZIP file
$encryptedzip = file_get_contents($zipname);
// Decrypt the data
$decryptedzip = openssl_decrypt($encryptedzip, 'AES-128-CBC', 'password', OPENSSL_RAW_DATA, '1234567890123456');
file_put_contents($zipname, $decryptedzip);
// Open and extract the decrypted ZIP
$zip = new ZipArchive();
if ($zip->open($zipname) === TRUE) {
$zip->extractTo('unzip/');
$zip->close();
echo 'ZIP archive has been decrypted and extracted.';
} else {
echo 'Failed to open ZIP archive.';
}
?>
The decryption uses the same algorithm and key as the encryption to ensure correct restoration.
By combining PHP's ZipArchive class with the openssl extension, you can effectively implement encryption and decryption of ZIP files, enhancing security during file transmission and storage. This guide and code examples aim to help you integrate these features into your projects.