PHP Zip context options

PHP's ZIP extension provides the zip:// stream wrapper for reading files from ZIP archives. Starting from PHP 7.2.0, it supports passwords for encrypted archives through context options.

Zip Context Options

The ZIP wrapper supports only one context option −

Option Type Description
password string Password for encrypted ZIP archives

Example

Note: This example requires file system access to create and read ZIP files.

First, create a password-protected ZIP archive −

<?php
$zip = new ZipArchive;
$zip->open('test.zip', ZipArchive::CREATE);
$zip->setPassword("MySecretPassword");
$zip->addFromString('test.txt', 'Hello, this is encrypted content!');
$zip->close();
echo "ZIP archive created with password protection.";
?>

Now, read the file from the encrypted ZIP archive using context options −

<?php
$opts = array(
    'zip' => array(
        'password' => 'MySecretPassword',
    ),
);

$context = stream_context_create($opts);
$content = file_get_contents('zip://test.zip#test.txt', false, $context);
echo $content;
?>
Hello, this is encrypted content!

Error Handling

If the password is incorrect or missing, the operation will fail −

<?php
// Wrong password example
$opts = array(
    'zip' => array(
        'password' => 'WrongPassword',
    ),
);

$context = stream_context_create($opts);
$content = file_get_contents('zip://test.zip#test.txt', false, $context);

if ($content === false) {
    echo "Failed to read file: Incorrect password or file not found.";
} else {
    echo $content;
}
?>

Conclusion

PHP's ZIP context options allow you to access password-protected ZIP archives using the zip:// wrapper. Always handle errors when working with encrypted archives to provide better user experience.

Updated on: 2026-03-15T09:22:40+05:30

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements