How to Password Protect a ZIP File in PHP
We can easily secure sensitive ZIP archives with encryption and password protection measures by calling a free, low-code API in PHP.
Our first order of business is to install the client SDK. We can install with Composer by executing the below command from the command line:
composer require cloudmersive/cloudmersive_document_convert_api_client
After that, we can turn our attention to authorization. We’ll need a free Cloudmersive API key to authorize our requests (this will allow us to make up to 800 API calls per month with no additional commitments).
Lastly, we can call the ZIP encryption and password protection function using the below code examples.
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
$apiInstance = new Swagger\Client\Api\ZipArchiveApi(
new GuzzleHttp\Client(),
$config
);
$encryption_request = new \Swagger\Client\Model\ZipEncryptionAdvancedRequest(); // \Swagger\Client\Model\ZipEncryptionAdvancedRequest | Encryption request
try {
$result = $apiInstance->zipArchiveZipEncryptAdvanced($encryption_request);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ZipArchiveApi->zipArchiveZipEncryptAdvanced: ', $e->getMessage(), PHP_EOL;
}
?>
We can structure our encryption request following the below JSON request example:
{
"InputFileContents": "string",
"Password": "string",
"EncryptionAlgorithm": "string"
}
Our encryption algorithm options are “AES-256” (recommended), “AES-128”, and “PK-Zip” (not recommended). If we leave “EncryptionAlgorithm” blank, it’ll default to “AES-256”.
No more code required — now it’s nice and simple to programmatically protect our sensitive ZIP archives.