Current Location: Home> Latest Articles> PHP Zip Context Options: How to Use Passwords and Stream Operations with ZIP Files

PHP Zip Context Options: How to Use Passwords and Stream Operations with ZIP Files

M66 2025-07-13

Introduction to PHP Zip Context Options

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.

How to Create an Encrypted ZIP File in PHP

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();

?>

Reading Files from a ZIP Archive

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);

?>

Conclusion

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.