Skip to content

Instantly share code, notes, and snippets.

@githubgobi
Created July 11, 2018 06:00
Show Gist options
  • Save githubgobi/6354b1218bfa1fe19e339a234d05a16e to your computer and use it in GitHub Desktop.
Save githubgobi/6354b1218bfa1fe19e339a234d05a16e to your computer and use it in GitHub Desktop.
Creating encrypted ZIP files with password in PHP

Creating encrypted ZIP files with password in PHP

You need at least PHP 7.2 to encrypt ZIP files with a password.

<?php

$zip = new ZipArchive();

$zipFile = __DIR__ . '/output.zip';
if (file_exists($zipFile)) {
    unlink($zipFile);
}

$zipStatus = $zip->open($zipFile, ZipArchive::CREATE);
if ($zipStatus !== true) {
    throw new RuntimeException(sprintf('Failed to create zip archive. (Status code: %s)', $zipStatus));
}

$password = 'top-secret';
if (!$zip->setPassword($password)) {
    throw new RuntimeException('Set password failed');
}

// compress file
$fileName = __DIR__ . '/test.pdf';
$baseName = basename($fileName);
if (!$zip->addFile($fileName, $baseName)) {
    throw new RuntimeException(sprintf('Add file failed: %s', $fileName));
}

// encrypt the file with AES-256
if (!$zip->setEncryptionName($baseName, ZipArchive::EM_AES_256)) {
    throw new RuntimeException(sprintf('Set encryption failed: %s', $baseName));
}

$zip->close();
@niraj-shah
Copy link

It's worth noting that zip files encrypted with ZipArchive::EM_AES_256 cannot be opened natively on Windows (i.e. using Explorer). But they can be extracted using 7zip or other third-party applications.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment