Last updated: August 29, 2026.
ZipArchive can package reports or unpack approved imports. Before extraction, inspect every entry because a malicious archive may try to write outside the destination.
Create an archive
<?php
$zip = new ZipArchive();
if ($zip->open(__DIR__ . '/reports.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) throw new RuntimeException('Cannot create archive.');
$zip->addFile(__DIR__ . '/sales.csv', 'sales.csv');
$zip->addFromString('README.txt', "Generated report archive\n");
$zip->close();Extract safely
- Reject absolute entry paths and parent-directory segments.
- Limit archive size and entry count.
- Extract only into a dedicated directory.
- Validate extracted file types before using them.
Treat extraction as an upload operation
An archive can contain unsafe paths, unexpected file types, very large expanded data, or thousands of small entries. Validate the complete entry list before extracting into a dedicated directory.
Test parent-directory paths, absolute paths, duplicate names, and a compressed file whose expanded size exceeds the limit. Clean the destination if validation or extraction fails.
- Limit entry count and expanded size.
- Reject links when the environment may create them.
- Authorize access to extracted files separately.
Keep resource limits explicit and make failure cleanup part of the example. Log enough context to diagnose the operation without recording passwords, private message bodies, or uploaded file contents.
Continue with secure uploads, temporary files, and DOCX text extraction.
Practical implementation check
Put the operation in a small function or service with explicit inputs and a clear failure result. Test invalid input, missing extensions, permission failures, and concurrent requests. Production logs should identify the operation and record ID without storing secrets or private content. Clean up partially created files or queue records when any later step fails.
Return a clear result to the caller and keep user-facing messages separate from detailed diagnostics. This makes the same code usable from a web request, command-line job, or queue worker.
Reference: PHP ZipArchive reference.