如何用PHP项目操作ZIP压缩包?

wen java案例 4

本文目录导读:

如何用PHP项目操作ZIP压缩包?

  1. 创建ZIP压缩包
  2. 解压ZIP文件
  3. 读取ZIP文件内容
  4. 删除ZIP中的文件
  5. 添加目录到压缩包
  6. 设置密码保护(ZIP加密)
  7. 压缩前检查文件是否存在
  8. 流式下载ZIP文件
  9. 注意事项

在PHP中操作ZIP压缩包主要使用内置的 ZipArchive 类,以下是常用的操作方法:

创建ZIP压缩包

<?php
$zip = new ZipArchive();
$zipFile = 'example.zip';
// 打开或创建ZIP文件
if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
    // 添加文件到压缩包
    $zip->addFile('file1.txt', 'new_file1.txt'); // 源文件, 压缩包内的文件名
    $zip->addFile('file2.txt');
    // 添加目录
    $zip->addEmptyDir('images');
    // 将字符串添加到压缩包
    $zip->addFromString('hello.txt', 'Hello World!');
    // 保存并关闭
    $zip->close();
    echo "压缩包创建成功";
} else {
    echo "无法创建压缩包";
}
?>

解压ZIP文件

<?php
$zip = new ZipArchive();
$zipFile = 'example.zip';
if ($zip->open($zipFile) === TRUE) {
    // 解压到指定目录
    $zip->extractTo('./extracted_files/');
    $zip->close();
    echo "解压成功";
} else {
    echo "无法打开压缩包";
}
?>

读取ZIP文件内容

<?php
$zip = new ZipArchive();
$zipFile = 'example.zip';
if ($zip->open($zipFile) === TRUE) {
    // 获取文件数量
    $fileCount = $zip->numFiles;
    echo "压缩包包含 $fileCount 个文件\n";
    // 遍历所有文件
    for ($i = 0; $i < $fileCount; $i++) {
        $stat = $zip->statIndex($i);
        echo "文件 {$i}: {$stat['name']} ({$stat['size']} bytes)\n";
    }
    // 读取特定文件内容
    $content = $zip->getFromName('hello.txt');
    echo "hello.txt 内容: " . $content;
    $zip->close();
}
?>

删除ZIP中的文件

<?php
$zip = new ZipArchive();
$zipFile = 'example.zip';
if ($zip->open($zipFile) === TRUE) {
    // 删除指定文件
    $zip->deleteName('file1.txt');
    // 删除指定索引的文件
    $zip->deleteIndex(0);
    $zip->close();
    echo "文件删除成功";
}
?>

添加目录到压缩包

<?php
function addFolderToZip($zip, $folder, $exclude = []) {
    $dir = opendir($folder);
    while ($file = readdir($dir)) {
        if (in_array($file, $exclude) || $file == '.' || $file == '..') {
            continue;
        }
        $filePath = $folder . '/' . $file;
        if (is_file($filePath)) {
            // 添加文件,保持目录结构
            $zip->addFile($filePath, str_replace('./', '', $filePath));
        } elseif (is_dir($filePath)) {
            // 递归添加子目录
            $zip->addEmptyDir(str_replace('./', '', $filePath));
            addFolderToZip($zip, $filePath, $exclude);
        }
    }
    closedir($dir);
}
$zip = new ZipArchive();
$zipFile = 'backup.zip';
if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
    addFolderToZip($zip, './my_folder', ['.git', 'node_modules']);
    $zip->close();
    echo "目录压缩成功";
}
?>

设置密码保护(ZIP加密)

<?php
$zip = new ZipArchive();
$zipFile = 'encrypted.zip';
if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
    // 设置密码(注意:这需要PHP 7.2+且只支持传统加密)
    $zip->setPassword('mypassword');
    // 添加文件并加密
    $zip->addFile('sensitive.txt');
    $zip->setEncryptionName('sensitive.txt', ZipArchive::EM_AES_256);
    $zip->close();
    echo "加密压缩包创建成功";
}
?>

压缩前检查文件是否存在

<?php
$zip = new ZipArchive();
$zipFile = 'test.zip';
if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
    $files = ['file1.txt', 'file2.txt', 'file3.txt'];
    foreach ($files as $file) {
        if (file_exists($file)) {
            $zip->addFile($file);
        } else {
            echo "警告: $file 不存在,已跳过\n";
        }
    }
    $zip->close();
}
?>

流式下载ZIP文件

<?php
$zip = new ZipArchive();
$zipFile = tempnam(sys_get_temp_dir(), 'zip');
if ($zip->open($zipFile, ZipArchive::CREATE) === TRUE) {
    $zip->addFile('document.pdf');
    $zip->addFile('image.jpg');
    $zip->close();
    // 设置下载头
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="download.zip"');
    header('Content-Length: ' . filesize($zipFile));
    readfile($zipFile);
    unlink($zipFile); // 删除临时文件
    exit;
}
?>

注意事项

  1. 安装扩展:确保PHP已安装zip扩展

    # Linux
    sudo apt-get install php-zip
    # 或
    sudo yum install php-zip
    # 在php.ini中启用
    extension=zip
  2. 文件大小限制:大文件压缩时注意内存和超时设置

    ini_set('memory_limit', '512M');
    set_time_limit(0);
  3. 权限问题:确保PHP有权限读写ZIP文件和目标目录

这些方法覆盖了大多数常见的ZIP操作场景,可以根据具体需求选择合适的方案。

抱歉,评论功能暂时关闭!