Compressing a file (zip) with a password in PHP

Webman -  
jordane45 Posted messages 30426 Registration date   Status Moderator Last intervention   -
Bonjour chers tous !

I have a version of PHP 5.6.3
I want to create a zip with a password via a PHP script.
With the function below I can compress my files but the password is not requested during decompression. (Password doesn't work)

Can someone help me?

Here is my script:

<?php
//**********function to compress files into zip********

function createZipFile($zipfile,$files){

$zip=new ZipArchive();

if($zip->open($zipfile, ZipArchive::CREATE) !== TRUE){

throw new Exception('Error: unable to open or create');

}

foreach($files as $file){

$zip->addFile($file);

$zip->setPassword('Password2');

}

$zip->close();

}

?>

2 answers

jordane45 Posted messages 30426 Registration date   Status Moderator Last intervention   4 830
 
Hello,

As indicated in the manual for this function https://www.php.net/manual/fr/ziparchive.setpassword.php ... it does not serve to protect an archive....
It is used to decompress an archive (already protected and that you want to extract from your php script)

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. 


As Erutan409 says ... (see the link I gave you earlier....) ... it would have been more appropriate to name this function "usePassword" .. ^^

--
Best regards,
Jordane
0
Webman
 
Ah Ok, thank you Jordane45 for explaining this principle to me.

But is there no way to add a password during compression?
0
Webman
 
Oh Okay, thanks Jordane45 for explaining this principle.

But is there a way to add a password during compression?
0
jordane45 Posted messages 30426 Registration date   Status Moderator Last intervention   4 830
 
not to my knowledge.
Or... you need to use a shell script (if you're on Linux) or possibly the 'system' command in PHP
 system('zip -P pass file.zip tonfichier'); 


but apparently it's not great... personally I've never tested it.
0