PHP 7.2: Encrypted ZIP files

PHP 7.2: Encrypted ZIP files

Encrypted ZIP files in PHP 7.2

Are you missing more WinRaR or 7zip features in PHP like using password for encrypting? Well say no more and update to PHP 7.2!

You can now encrypt or decrypt your ZIP files by providing additional context of password passed to the zip:// stream. The ZipArchive is now implementing a Countable interface to make it compatible with each other.

$zip = new ZipArchive();
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
    $zip->addFromString('test.txt', 'file content goes here');
    $zip->setEncryptionName('test.txt', ZipArchive::EM_AES_256, 'password');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}

You can use any of the following ZipArchive constants:

ZipArchive::EM_NONE (integer)
No encryption, since PHP 7.2.0, PECL zip 1.14.0
ZipArchive::EM_AES_128 (integer)
AES 128 encryption, since PHP 7.2.0, PECL zip 1.14.0
ZipArchive::EM_AES_192 (integer)
AES 1192 encryption, since PHP 7.2.0, PECL zip 1.14.0
ZipArchive::EM_AES_256 (integer)
AES 256 encryption, since PHP 7.2.0, PECL zip 1.14.0

Reference

PHP 7 News & Updates v7.0 - 7.4 - Book coverPHP 7 News & Updates v7.0 – 7.4 Book https://www.amazon.com/PHP-News-Updates-v7-0-7-4/dp/1727202481/

Rate this artcile
[Total: 1 Average: 5]

3 thoughts on “PHP 7.2: Encrypted ZIP files

    • Hi Peter, you can decrypt files in PHP with build-in: ZipArchive::extractTo() method, like so:

      $zip = new ZipArchive();
      $zip->open(‘test.zip’);
      $zip->extractTo(‘/my/folder/’);

      • Also some of the info from PHP docs:

        As of PHP 7.2.0 and libzip 1.2.0 the password is used to decompress the archive, and is also the default password for ZipArchive::setEncryptionName() and ZipArchive::setEncryptionIndex(). Formerly, this function only set the password to be used to decompress the archive; it did not turn a non-password-protected ZipArchive into a password-protected ZipArchive.

Comments are closed.