2

I use PHP ZIPArchive to create zip file from folder and user doesn't want to change the original file created date when download. my code is below and is there any option that helps to keep the file created date?

    function zipData($source, $destination, $fname) {
    if (extension_loaded('zip')) {
        if (file_exists($source)) {
            $zip = new ZipArchive();
            if ($zip->open($destination, ZIPARCHIVE::CREATE)) {
                $source = realpath($source);
                if (is_dir($source)) {
                    $iterator = new RecursiveDirectoryIterator($source);
                    $iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS);
                    $files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);
                    foreach ($files as $file) {
                        $file = realpath($file);
                        if (is_dir($file)) {
                            $zip->addEmptyDir(str_replace($source . '/', '', $fname . '/' . $file . '/'));
                        } else if (is_file($file)) {
                            $zip->addFromString(str_replace($source . '/', '', $fname . '/'. $file), file_get_contents($file));
                        }
                    }
                } else if (is_file($source)) {
                    $zip->addFromString(basename($source), file_get_contents($source));
                }
            }
            return $zip->close();
        }
    }
    return false;
}
Thameera
  • 33
  • 4
  • This has been already discussed here: https://stackoverflow.com/questions/35083308/php-download-file-and-preserve-timestamp Are you looking for this? – Marvin Klar Mar 07 '19 at 13:10
  • This is not the one I'm looking for. My issue is when zip file create all the files inside the zip file will change to time they request the zip file. I want to keep the original time stamp of the file inside the zip file. – Thameera Mar 08 '19 at 01:51
  • Since I currently don't have the possiblity to test it, I have to ask, if you already have tried using `$zip->addFile("yourfilename")` instead of `$zip->addFromString()`. Because this will `Add[...] a file to a ZIP archive from the given path` and don't create a new file by `Add[ing] a file to a ZIP archive using its contents`. – Marvin Klar Mar 08 '19 at 08:01
  • Great to hear that! I just created a concluding answer. Feel free to accept it. – Marvin Klar Mar 12 '19 at 08:03

1 Answers1

0

As described in the comments, we have to use $zip->addFile("yourfilename") instead of $zip->addFromString(). Because this will Add[...] a file to a ZIP archive from the given path and don't create a new file by Add[ing] a file to a ZIP archive using its contents.

Marvin Klar
  • 1,869
  • 3
  • 14
  • 32