ZIP a file and protect with a password in PHP
Asked Answered
S

6

13

I'm having this code to zip files but i need to protect this file with a password

$file = 'backup.sql';
$zipname = $file.'.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
ZipArchive::setPassword('123456');
//$zip->setPassword("123456");
$zip->addFile($file);
$zip->close();

when i use $zip->setPassword i don't get any errors but the file is not protected at all and when i use ZipArchive::setPassword i get this error "Fatal error: Non-static method ZipArchive::setPassword() cannot be called statically"

So how to zip a file in php and protect it with a password?

Slotnick answered 3/10, 2016 at 14:2 Comment(1)
Possible duplicate of How to create password protected archive file in PHP?Eccentric
E
6

Yes, creation of password protected archives is not supported (they will be created simply as non-protected archives).
But, still it can be used to extract password protected archives.

Returning to the problem.
You always can just

<?php echo system('zip -P pass file.zip file.txt'); ?>

(this will work both on Windows and our beloved Linux)

But, if it not fits into your requirements, let's continue.
I would suggest you to use DotNetZip (Windows only), you will exactly dynamically generate AES-encrypted zip archives from PHP.

<?php
// origin: https://mcmap.net/q/518161/-create-an-encrypted-zip-archive-with-php
try
{
  $fname = "zip-generated-from-php-" . date('Y-m-d-His') . ".zip";
  $zipOutput = "c:\\temp\\" . $fname;
  $zipfact = new COM("Ionic.Zip.ZipFile");
  $zip->Name = $zipOutput;
  $dirToZip= "c:\\temp\\psh";
  # Encryption:  3 => 256-bit AES.  
  #     2 => 128-bit AES.  
  #     1 => PKZIP (Weak).  
  #     0 => None
  $zip->Encryption = 3;
  $zip->Password = "AES-Encryption-Is-Secure";
  $zip->AddDirectory($dirToZip);
  $zip->Save();
  $zip->Dispose();

  if (file_exists($zipOutput))
  {
    header('Cache-Control: no-cache, must-revalidate');
    header('Content-Type: application/x-zip'); 
    header('Content-Disposition: attachment; filename=' . $fname);
    header('Content-Length: ' . filesize($zipOutput));
    readfile($zipOutput);
    unlink($zipOutput);
  }
  else 
  {
    echo '<html>';
    echo '  <head>';
    echo '  <title>Calling DotNetZip from PHP through COM</title>';
    echo '  <link rel="stylesheet" href="basic.css"/>';
    echo '  </head>';
    echo '<body>';
    echo '<h2>Whoops!</h2>' . "<br/>\n";
    echo '<p>The file was not successfully generated.</p>';
    echo '</body>';
    echo '</html>';
  } 
}
catch (Exception $e) 
{
    echo '<html>';
    echo '  <head>';
    echo '  <title>Calling DotNetZip from PHP through COM</title>';
    echo '  <link rel="stylesheet" href="basic.css"/>';
    echo '  </head>';
    echo '<body>';
    echo '<h2>Whoops!</h2>' . "<br/>\n";
    echo '<p>The file was not successfully generated.</p>';
    echo '<p>Caught exception: ',  $e->getMessage(), '</p>', "\n";
    echo '<pre>';
    echo $e->getTraceAsString(), "\n";
    echo '</pre>';
    echo '</body>';
    echo '</html>';
}

?>

But still, this is very dirty solution and more of that, not works on Linux.

So, although PHP is a mature language, there is no adequate method (excluding custom extension or something like that) to achieve such a simple task with pure PHP.
What you also can do, is to wait until PHP 7.2 will be available for production (cuz ZipArchive::setEncryptionName is implemented (thanks to Pierre and Remi)).
But, until then you also can try to port php_zip >= 1.14.0 to PHP < 7.2, but there is currently no compiled binaries available, so you have to compile it yourself and try if it is possible at all (I believe it is).
p.s. I would try it, but have no VS2015+ on my PC right now.

Eccentric answered 19/7, 2017 at 22:17 Comment(0)
P
21

Use PHP 7.2 to create password protected zip file:

$zip = new ZipArchive;
$res = $zip->open('filename.zip', ZipArchive::CREATE); //Add your file name
if ($res === TRUE) {
   $zip->addFromString('FILENAME_WITH_EXTENSION', 'file content goes here'); //Add your file name
   $zip->setEncryptionName('FILENAME_WITH_EXTENSION', ZipArchive::EM_AES_256, 'PASSWORD'); //Add file name and password dynamically
   $zip->close();
   echo 'ok';
} else {
   echo 'failed';
}
Polenta answered 28/8, 2018 at 6:52 Comment(0)
E
6

Yes, creation of password protected archives is not supported (they will be created simply as non-protected archives).
But, still it can be used to extract password protected archives.

Returning to the problem.
You always can just

<?php echo system('zip -P pass file.zip file.txt'); ?>

(this will work both on Windows and our beloved Linux)

But, if it not fits into your requirements, let's continue.
I would suggest you to use DotNetZip (Windows only), you will exactly dynamically generate AES-encrypted zip archives from PHP.

<?php
// origin: https://mcmap.net/q/518161/-create-an-encrypted-zip-archive-with-php
try
{
  $fname = "zip-generated-from-php-" . date('Y-m-d-His') . ".zip";
  $zipOutput = "c:\\temp\\" . $fname;
  $zipfact = new COM("Ionic.Zip.ZipFile");
  $zip->Name = $zipOutput;
  $dirToZip= "c:\\temp\\psh";
  # Encryption:  3 => 256-bit AES.  
  #     2 => 128-bit AES.  
  #     1 => PKZIP (Weak).  
  #     0 => None
  $zip->Encryption = 3;
  $zip->Password = "AES-Encryption-Is-Secure";
  $zip->AddDirectory($dirToZip);
  $zip->Save();
  $zip->Dispose();

  if (file_exists($zipOutput))
  {
    header('Cache-Control: no-cache, must-revalidate');
    header('Content-Type: application/x-zip'); 
    header('Content-Disposition: attachment; filename=' . $fname);
    header('Content-Length: ' . filesize($zipOutput));
    readfile($zipOutput);
    unlink($zipOutput);
  }
  else 
  {
    echo '<html>';
    echo '  <head>';
    echo '  <title>Calling DotNetZip from PHP through COM</title>';
    echo '  <link rel="stylesheet" href="basic.css"/>';
    echo '  </head>';
    echo '<body>';
    echo '<h2>Whoops!</h2>' . "<br/>\n";
    echo '<p>The file was not successfully generated.</p>';
    echo '</body>';
    echo '</html>';
  } 
}
catch (Exception $e) 
{
    echo '<html>';
    echo '  <head>';
    echo '  <title>Calling DotNetZip from PHP through COM</title>';
    echo '  <link rel="stylesheet" href="basic.css"/>';
    echo '  </head>';
    echo '<body>';
    echo '<h2>Whoops!</h2>' . "<br/>\n";
    echo '<p>The file was not successfully generated.</p>';
    echo '<p>Caught exception: ',  $e->getMessage(), '</p>', "\n";
    echo '<pre>';
    echo $e->getTraceAsString(), "\n";
    echo '</pre>';
    echo '</body>';
    echo '</html>';
}

?>

But still, this is very dirty solution and more of that, not works on Linux.

So, although PHP is a mature language, there is no adequate method (excluding custom extension or something like that) to achieve such a simple task with pure PHP.
What you also can do, is to wait until PHP 7.2 will be available for production (cuz ZipArchive::setEncryptionName is implemented (thanks to Pierre and Remi)).
But, until then you also can try to port php_zip >= 1.14.0 to PHP < 7.2, but there is currently no compiled binaries available, so you have to compile it yourself and try if it is possible at all (I believe it is).
p.s. I would try it, but have no VS2015+ on my PC right now.

Eccentric answered 19/7, 2017 at 22:17 Comment(0)
G
3

ZipArchive::setPassword This function only sets the password to be used to decompress the archive; it does not turn a non-password-protected ZipArchive into a password-protected ZipArchive.

working code:

$file = 'file_name_to_be_compressed.extension'

system('zip -P ZIP_PASSWORD '.$file.'.zip '.$file);

Gilroy answered 3/10, 2016 at 14:11 Comment(1)
#646695 <- here you can find ways to use a password on a zip file.Gilroy
A
3

When adding multiple files into the zip archive, you can set password at once with the setPassword() method.

$zip = new ZipArchive();
$zip->open('zip_name.zip', ZipArchive::CREATE);

foreach ($files as $file) {
    $zip->addFile($file['path'], $file['name']);
    $zip->setEncryptionName($file['name'], ZipArchive::EM_AES_256);
}

$zip->setPassword('passW0rd');    
$zip->close();
Aphotic answered 31/12, 2022 at 12:9 Comment(0)
G
2

Since PHP 7.2 you can use setEncryptionName to create password protected ZIP archive.

Gley answered 23/5, 2018 at 13:50 Comment(0)
B
0

As it is described on the documentation:

This function only sets the password to be used to decompress the archive; it does not turn a non-password-protected ZipArchive into a password-protected ZipArchive.

If you want to encrypt a zip archive I'd suggest google a bit :)

Ballistics answered 3/10, 2016 at 14:17 Comment(1)
Woops - there was someone faster then me 🙈Ballistics

© 2022 - 2025 — McMap. All rights reserved.