在 PHP 中建立一個 Zip 檔案

John Wachira 2024年2月15日
  1. 使用 PHP 建立一個 Zip 檔案
  2. 使用 PHP 解壓縮 Zip 檔案
在 PHP 中建立一個 Zip 檔案

本教程將演示建立一個 zip 檔案並使用 PHP 解壓縮該檔案,並在該 zip 檔案的資料夾中新增檔案。

使用 PHP 建立一個 Zip 檔案

下面的示例程式碼將建立一個 zip 檔案 tutorial.zip,並新增檔案。

在我們的 htdocs 目錄中,我們有 Files to zip 資料夾,其中包含兩個檔案。我們將壓縮目錄 Files to zip

<?php
// Enter the name of directory
$pathdir = "Files to zip/";

//Create a name for the zip folder
$zipcreated = "Files to zip.zip";

// Create new zip class
$zip = new ZipArchive;

if($zip -> open($zipcreated, ZipArchive::CREATE ) === TRUE) {

    // Store the files in our `Files to zip` zip file.
    $dir = opendir($pathdir);

    while($file = readdir($dir)) {
        if(is_file($pathdir.$file)) {
            $zip -> addFile($pathdir.$file, $file);
}
}
}
?>

此程式碼在我們的根目錄中建立一個新的 zip,Files to zip,如下所示。

壓縮影象的檔案

我們使用目錄 Files to zip 建立 zip 資料夾 Files to zip。我們的目錄有兩個檔案,insert.phpLoader.php

我們應該在我們的 zip 資料夾中找到上述檔案。讓我們來看看。

zip 檔案裡面

使用 PHP 解壓縮 Zip 檔案

讓我們看看如何使用 PHP 解壓縮 zip 檔案。

例子:

<?php
// Create new zip class
$zip = new ZipArchive;

// Add zip filename which needs to unzip

$zip->open('Files to zip.zip');

// Extracts to current directory
$zip->extractTo('./Files to zip');

$zip->close();
?>

輸出:

解壓壓縮檔案

我們使用程式碼將 Files to zip.zip 解壓縮到 Files to zip 資料夾。

作者: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

相關文章 - PHP Zip