Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 281
Badal Avatar asked Sep 01 '25 22:09

Badal


2 Answers

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.

like image 66
the_nuts Avatar answered Sep 03 '25 15:09

the_nuts


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();
}
like image 44
Badal Avatar answered Sep 03 '25 14:09

Badal