4

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?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Badal
  • 3,738
  • 4
  • 33
  • 60

4 Answers4

6

I improved Badal's answer to apply to all the files in the ZIP (directories will still have the current timestamp):

$res = $zip->open($filename);
if($res === true) {
    $zip->extractTo($dataDir);

    for($i=0; $i<$zip->numFiles; $i++){
        touch($dataDir . $zip->statIndex($i)['name'], $zip->statIndex($i)['mtime']);
    }

    $zip->close();
}

$dataDir needs to end with a slash.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
the_nuts
  • 5,634
  • 1
  • 36
  • 68
  • I used this script and the directories timestamps _were_ updated as well (with PHP 7.3.12). – Goozak Dec 16 '19 at 19:51
4

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();
}
Badal
  • 3,738
  • 4
  • 33
  • 60
  • Actually this changes only the first file, (with index=0), you need to cycle all the files to apply to the whole zip – the_nuts Apr 16 '18 at 17:07
0

There's an open bug about this with a pull request to fix it, but it hasn't been applied yet

zootropo
  • 2,441
  • 3
  • 31
  • 48
0

In zip archives, the date and time are encoded in standard MS-DOS format (https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT). This means that date and time are according to the local time of the system that created the zip archive.

The mtime returned by statIndex assumes that the local time of the system that created the zip archive was UTC (GMT), which is rarely true.

Jean-Luc
  • 33
  • 3