0

我正在使用 php 7.4(lib-zip 版本 1.6.1)创建一个 zip 存档,没有任何问题。

现在我尝试用密码保护这些 zip 存档。不仅用于使用 php 加密,而且通常用于加密。我找到了这个教程。它做了它应该做的,但我无法再读取 zip 存档的文件了。如果我双击存档,将打开密码提示,但它不适用于源代码中的密码。我还复制并粘贴了它以防止任何键盘问题。

<?php

$zip = new ZipArchive();
$filePath = sprintf('%s/test/', __DIR__);
$fileName = 'test.zip';
$absoluteFilePath = $filePath . $fileName;
$excludeFolderNames = [
  '.',
  '..',
  '.DS_Store',
  $fileName,
];

$zipFlag = ZipArchive::CREATE;
if (file_exists($absoluteFilePath)) {
    $zipFlag = ZipArchive::OVERWRITE;
}

$createFile = $zip->open($absoluteFilePath, $zipFlag);
if (true !== $createFile) {
    throw new RuntimeException(sprintf('could not open file in "%s" caused by %s', $fileName, $createFile));
}

$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($filePath));
$password = 'top-secret';
if (!$zip->setPassword($password)) {
    throw new RuntimeException('Set password failed');
}

/** @var SplFileInfo $value */
foreach ($iterator as $key => $value) {
    if (in_array($value->getFilename(), $excludeFolderNames)) {
        continue;
    }

    $cleanFilePath = realpath($key);
    if (!$cleanFilePath) {
        throw new RuntimeException(sprintf('could not create real path from filepath: %s', $key));
    }

    $zipName = str_replace($filePath, '', $cleanFilePath);
    if (!$zip->addFile($cleanFilePath, $zipName)) {
        throw new RuntimeException(sprintf('Add file failed: %s', $cleanFilePath));
    }

    if (!$zip->setEncryptionName($zipName, ZipArchive::EM_AES_256)) {
        throw new RuntimeException(sprintf('Set encryption failed: %s', $zipName));
    }
}

$zip->close();

有人有同样的问题还是我有问题?

更新 I: 我认为它解决了将 zip 文件保存在我要压缩的文件夹之外的问题。所以我更改了以下行:

$absoluteFilePath = sprintf('%s/%s', __DIR__, $fileName);

过了一会儿,错误又出现了。

我发现的一个可能原因是 .DS_Store 文件。在我的示例中,我将它们排除在外。但是错误又出现了。

更新二: 另一个问题是,如果所有文件都是空的,则没有密码提示。

更新三: 相同的代码适用于没有换行符的文件,但如果文件有多行,则会发生错误。

4

1 回答 1

0

我在php-bugtracker找到了帮助。事实证明,我可以提取所有带有zip 扩展名的文件,就像之前试图告诉我的评论一样。现在我等待新的libzip版本 1.7.0,其中默认的 zip 加密可用。在此之后,我希望我可以在没有任何扩展名的情况下提取我的文件。

于 2020-05-26T14:55:08.617 回答