Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZIP a file and protect with a password in PHP

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?

like image 709
PHP User Avatar asked Oct 03 '16 14:10

PHP User


1 Answers

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';
}
like image 110
Shahaji Deshmukh Avatar answered Sep 21 '22 11:09

Shahaji Deshmukh