Backend Development 7 min read

Extracting and Creating RAR and ZIP Archives with PHP

This article explains how to use PHP's RarArchive and ZipArchive classes to extract RAR and ZIP files, create ZIP archives, and compress folders into RAR archives, providing step‑by‑step code examples and detailed explanations for each operation.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Extracting and Creating RAR and ZIP Archives with PHP

PHP, a classic server‑side scripting language, can handle both RAR and ZIP archives for extraction and creation.

Extracting a RAR archive

To extract a RAR file you need the RarArchive extension. After confirming the extension is installed, use the RarArchive class as shown below.

$archive = RarArchive::open('example.rar'); // 打开RAR压缩包
if ($archive === false) {
    die("无法打开RAR文件");
}
$entries = $archive->getEntries(); // 获取RAR文件的实体
foreach ($entries as $entry) {
    $entry->extract('path/to/extract'); // 解压缩RAR文件到指定目录
}
$archive->close(); // 关闭RAR压缩包

The code opens the archive, iterates over each entry, extracts it to the specified directory, and finally closes the archive.

Extracting a ZIP archive

ZIP extraction is simpler because PHP provides the built‑in ZipArchive class with no extra dependencies.

$zip = new ZipArchive();
if ($zip->open('example.zip') === true) { // 打开ZIP压缩包
    $zip->extractTo('path/to/extract'); // 解压缩ZIP文件到指定目录
    $zip->close(); // 关闭ZIP压缩包
} else {
    die("无法打开ZIP文件");
}

This snippet opens the ZIP file, extracts its contents, and closes the archive.

Creating a ZIP archive

To create a ZIP file, use ZipArchive::CREATE and add files with addFile .

$zip = new ZipArchive();
if ($zip->open('example.zip', ZipArchive::CREATE) === true) { // 创建ZIP压缩包
    $zip->addFile('path/to/file1.txt', 'file1.txt'); // 向ZIP压缩包中添加文件
    $zip->addFile('path/to/file2.txt', 'file2.txt');
    $zip->close(); // 关闭ZIP压缩包
} else {
    die("无法创建ZIP文件");
}

The example creates example.zip , adds two files, and closes the archive.

Compressing a folder into a RAR archive

Compression to RAR uses the same RarArchive class. The following function recursively adds a directory and allows a Chinese comment to be set.

<?php
/**
 * 使用RarArchive压缩文件夹,并添加中文注释
 * @param string $source       目标文件夹路径
 * @param string $destination  压缩文件保存路径
 * @param string $comment      压缩文件的中文注释
 * @return bool  压缩成功返回true,否则返回false
 */
function compressFolderWithComment($source, $destination, $comment)
{
    $archive = RarArchive::open($destination, RarArchive::CREATE);
    if ($archive === false) {
        return false;
    }
    $rar_comment = iconv("UTF-8", "GBK", $comment);
    $files = scandir($source);
    foreach ($files as $file) {
        if ($file == "." || $file == "..") {
            continue;
        }
        $fullPath = $source . '/' . $file;
        if (is_dir($fullPath) {
            // 如果是文件夹,则递归压缩
            if (!compressFolderWithComment($fullPath, $destination, $comment)) {
                return false;
            }
        } else {
            // 如果是文件,则添加到压缩文件
            $rar_file = iconv("UTF-8", "GBK", $file);
            $entry = $archive->addFile($fullPath, $rar_file);
            // 设置文件的注释
            $entry->setComment(null, $rar_comment);
        }
    }
    $archive->setComment($rar_comment);
    $archive->close();
    return true;
}
// 使用示例
$source = '/path/to/source/folder'; // 源文件夹路径
$destination = '/path/to/destination/archive.rar'; // 压缩文件保存路径
$comment = '这是压缩文件的中文注释'; // 压缩文件的中文注释
if (compressFolderWithComment($source, $destination, $comment)) {
    echo '文件夹压缩成功!';
} else {
    echo '文件夹压缩失败。';
}
?>

These examples demonstrate that handling RAR and ZIP archives in PHP is straightforward using built‑in classes or extensions, enabling developers to extract, create, and compress files efficiently.

Backend DevelopmentPHPfile compressionziprar
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.