Search code examples
phpzipphp-ziparchive

Keep the modified date of files extracted from the ZIP using PHP ZipArchive


I am using ZipArchive to extract files from ZIP.

Here is the code I am using

$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
    $zip->extractTo('test/');
    $zip->close();
}

It works fine but the last modified date of extracted files changes to current time.

How I can keep the original last modified date of the extracted files?


Solution

  • I found a way to do it by using mtime value supplied by ZipArchive::statIndex

    It changes the modified date of the extracted file after extraction.

    Here is the final code:

    $zip = new ZipArchive;
    $res = $zip->open($file);
    if ($res === TRUE) {
        $filename = $mtime = $zip->statIndex(0)['name'];
        $zip->extractTo('test/');
        touch('test/'.$filename, $zip->statIndex(0)['mtime']); // Change the modified date of the extracted file.
        $zip->close();
    }