In PHP development, working with ZIP archives using the ZipArchive class is very common. Sometimes, there is a need to modify the timestamps of files inside these archives to meet specific requirements. This article explains how to achieve this using ZipArchive.
ZipArchive is a built-in PHP class designed for creating, opening, reading, and modifying ZIP files. It offers various methods to manage archive contents efficiently.
First, open the target ZIP archive with the ZipArchive class:
$zip = new ZipArchive();
$zipFile = 'path/to/your/zip/file.zip';
if ($zip->open($zipFile) === true) {
// Continue with operations
}
Then, use the statIndex method to retrieve detailed info about a file at a given index, including its timestamp:
$fileIndex = 0; // File index inside the archive
$fileInfo = $zip->statIndex($fileIndex);
$lastModifiedTime = $fileInfo['mtime'];
Modify the timestamp, for example, set it to the current time:
$lastModifiedTime = time();
Apply the new timestamp to the file using the setModificationTime method:
$zip->setModificationTime($fileIndex, $lastModifiedTime);
Finally, close the archive to save changes:
$zip->close();
Here is a complete example demonstrating how to update the timestamp of the first file inside a ZIP archive:
$zip = new ZipArchive();
$zipFile = 'path/to/your/zip/file.zip';
if ($zip->open($zipFile) === true) {
$fileIndex = 0;
$fileInfo = $zip->statIndex($fileIndex);
$lastModifiedTime = $fileInfo['mtime'];
$lastModifiedTime = time();
$zip->setModificationTime($fileIndex, $lastModifiedTime);
$zip->close();
}
This code updates the timestamp of the file at index 0 to the current time.
Using PHP's ZipArchive class, modifying file timestamps inside ZIP archives is straightforward. This article provided a clear process and example to help you customize file times within compressed files as needed.