The ZIP extension in PHP provides robust support for working with ZIP files. Starting from PHP 7.2.0, it supports setting passwords for encrypted ZIP files. By configuring the ZIP context options, you can specify a password when reading ZIP files to unlock the encrypted contents.
Here is an example of how to create and encrypt a ZIP file:
<?php
$zip
=
new
ZipArchive;
$zip
->open(
'test.zip'
);
$zip
->setPassword(
"MySecretPassword"
);
$zip
->addFile(
'c:/xampp/php/test.txt'
,
'test.txt'
);
$zip
->close();
?>
To read files from an encrypted ZIP file, you can use the following example, which sets the context options and passes the password to access the contents of the ZIP file:
<?php
$opts
=
array
(
'zip'
=>
array
(
'password'
=>
'secret'
,
),
);
$context
= stream_context_create(
$opts
);
echo
file_get_contents
(
'zip://test.zip#test.txt'
, false,
$context
);
?>
This article provides a detailed guide on how to use the PHP ZIP extension to set password protection on ZIP files and how to read encrypted files from a ZIP archive using stream context options. With these methods, you can efficiently manage and interact with encrypted ZIP files in PHP.