如何使用 PHP 创建 zip 文件 [英] How to create a zip file using PHP

查看:35
本文介绍了如何使用 PHP 创建 zip 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文件一个文件夹保存到另一个文件夹.zip 文件夹 放在不同的目录中.我写了以下代码:

I am trying to save files from one folder to another. zip folder placed in different directory. And I have written the following codes:

archive.php

<?php
    $zip = new ZipArchive();
    $zip->open('example.zip',  ZipArchive::CREATE);
    $srcDir = "/home/sam/uploads/";
    $files= scandir($srcDir);
    //var_dump($files);
    unset($files[0],$files[1]);
    foreach ($files as $file) {
        $zip->addFile("{$file}");    
    }
    $zip->close();
?>

但遗憾的是我无法创建 .zip 文件夹.有什么我遗漏的步骤吗?

But sadly I am not able to create the .zip folder. Is there any step I missed?

推荐答案

$zip = new ZipArchive();

$DelFilePath="first.zip";

if(file_exists($_SERVER['DOCUMENT_ROOT']."/TEST/".$DelFilePath)) {

        unlink ($_SERVER['DOCUMENT_ROOT']."/TEST/".$DelFilePath); 

}
if ($zip->open($_SERVER['DOCUMENT_ROOT']."/TEST/".$DelFilePath, ZIPARCHIVE::CREATE) != TRUE) {
        die ("Could not open archive");
}
    $zip->addFile("file_path","file_name");

// close and save archive

$zip->close(); 

这里的 TEST 是您的项目文件夹名称.

Here TEST is your project folder name.

您可以根据需要定义路径.

You can define path as you want.

这篇关于如何使用 PHP 创建 zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆