使用PHP保存文件属性来压缩文件夹

问题描述 投票:2回答:1

我使用PHP ZIPArchive从文件夹创建zip文件,用户不希望在下载时更改原始文件创建日期。我的代码在下面,是否有任何选项有助于保持文件创建日期?

    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;
}
php ziparchive
1个回答
0
投票

如评论中所述,我们必须使用$zip->addFile("yourfilename")而不是$zip->addFromString()。因为这将Add[...] a file to a ZIP archive from the given path并且不会由Add[ing] a file to a ZIP archive using its contents创建新文件。

© www.soinside.com 2019 - 2024. All rights reserved.