A partir de php 7.2 (que se lanzó hace unas horas), la forma correcta de hacerlo es utilizar la funcionalidad adicional incluida en ZipArchive código nativo php. (Gracias a abraham-tugalov por señalar que este cambio iba a venir)
Ahora la respuesta simple es como la siguiente:
<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
$zip->setPassword('secret_used_as_default_for_all_files'); //set default password
$zip->addFile('thing1.txt'); //add file
$zip->setEncryptionName('thing1.txt', ZipArchive::EM_AES_256); //encrypt it
$zip->addFile('thing2.txt'); //add file
$zip->setEncryptionName('thing2.txt', ZipArchive::EM_AES_256); //encrypt it
$zip->close();
echo "Added thing1 and thing2 with the same password\n";
} else {
echo "KO\n";
}
?>
Pero también puede establecer el método de cifrado por el índice y no el nombre, y se puede configure cada contraseña por archivo ... y especifique las opciones de cifrado más débiles, usando newly supported encryption options.
Este ejemplo ejerce estas opciones más complejas.
<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
//being here means that we were able to create the file..
//setting this means that we do not need to pass in a password to every file, this will be the default
$zip->addFile('thing3.txt');
//$zip->setEncryptionName('thing3.txt', ZipArchive::EM_AES_128);
//$zip->setEncryptionName('thing3.txt', ZipArchive::EM_AES_192);
//you should just use ZipArchive::EM_AES_256 unless you have super-good reason why not.
$zip->setEncryptionName('thing3.txt', ZipArchive::EM_AES_256, 'password_for_thing3');
$zip->addFile('thing4.txt');
//or you can also use the index (starting at 0) of the file...
//which means the following line should do the same thing...
//but just referencing the text.txt by index instead of name..
//$zip->setEncryptionIndex(1, ZipArchive::EM_AES_256, 'password_for_thing_4'); //encrypt thing4, using its index instead of its name...
$zip->close();
echo "Added thing3 and thing4 with two different passwords\n";
} else {
echo "KO\n";
}
?>
El soporte subyacente para el cifrado zip está habilitado porque libzip 1.2.0 introdujo el soporte para el cifrado. Por lo tanto, necesitará tener php 7.2 y libzip 7.2 para ejecutar este código ... Esperamos que esta nota sea confusa en esta respuesta "muy pronto"
gracias, intentaré esto. está en un servidor linux estoy trabajando, por lo que el complemento no será necesario. – Digits
El cifrado ZIP es bastante débil, hay ataques que producen una contraseña activa (si no necesariamente la misma contraseña que se usó originalmente) en relativamente poco tiempo. – bobince
Esta respuesta es muy peligrosa. La encriptación utilizada por esta respuesta es terriblemente débil. * No * es la encriptación moderna basada en AES. –