ZIP a file and protect with a password in PHP

PHP User picture PHP User · Oct 3, 2016 · Viewed 23k times · Source

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?

Answer

Shahaji Deshmukh picture Shahaji Deshmukh · Aug 28, 2018

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';
}