xref: /PHP-8.3/ext/zip/examples/encryption.php (revision 58b17906)
1<?php
2error_reporting(E_ALL);
3if (!extension_loaded('zip')) {
4    dl('zip.so');
5}
6
7$name = __DIR__ . '/encrypted.zip';
8$pass = 'secret';
9$file = 'foo.php';
10
11echo "== Create with per file password\n";
12
13$zip  = new ZipArchive;
14$zip->open($name, ZIPARCHIVE::CREATE | ZipArchive::OVERWRITE);
15$zip->addFile(__FILE__, $file);
16$zip->setEncryptionName($file, ZipArchive::EM_AES_256, $pass);
17$zip->close();
18
19echo "== Create with global password\n";
20
21$zip  = new ZipArchive;
22$zip->open($name, ZIPARCHIVE::CREATE | ZipArchive::OVERWRITE);
23$zip->setPassword($pass);
24$zip->addFile(__FILE__, $file);
25$zip->setEncryptionName($file, ZipArchive::EM_AES_256);
26$zip->close();
27
28echo "== Stat\n";
29
30$zip->open($name);
31print_r($zip->statName($file));
32
33echo "== Read\n";
34
35$zip->setPassword($pass);
36$text = $zip->getFromName($file);
37printf("Size = %d\n", strlen($text));
38$zip->close();
39
40echo "== Stream with context\n";
41
42$ctx = stream_context_create(array(
43    'zip' => array(
44        'password' => $pass
45    )
46));
47$text = file_get_contents("zip://$name#$file", false, $ctx);
48printf("Size = %d\n", strlen($text));
49