网站首页 » PHP » PHP ZIP多层文件夹压缩代码

PHP ZIP多层文件夹压缩代码

April 1, 2019 PHP

PHP ZIP多层文件夹压缩代码

前言...
找了好久,都没找到适合自己的函数,遂自建一个。

本函数可以接受多个源文件(或文件夹)同时压缩,例如使用数组传值:

$zip_result = createZip( array('A.php', 'B.txt', 'logo.png', '/var/www/assets/css/'),      'result.zip' );

$zip_result = createZip( ‘/path-to-source-folder/’,  'result.zip' );

$zip_result = createZip( 'index.html',      'result.zip' );

注意:

  • 1.需要两个自建函数配合:createZip()  +   recursive_get_files_by_path_of_folder() 
  • 2.主函数一个输出的结果$return'data'['url']需要自己去补充,现在为空。(可选)
<?php
define('BASE_PATH',str_replace('\\','/',realpath(dirname(__FILE__).'/'))."/");
/**
 * 
 * createZip - 创建压缩包,for文件夹/文件
 * 
 * @param type string-or-array $from  
 *        => 字符串 '/path/to/source/file/or/folder/'
 *        => 或者 包含字符串的数组  array('fileA','FolderA','fileB')
 * @param type string $to 
 *        => 字符串 '/path/to/output.zip'
 * @return array
 *        => array(
 *             'success' => false, 
 *             'message' => '失败原因', 
 *             'data' => array(
 *                 'zipFile' => array(zip文件的信息)
 *             ) 
 *           )
 * @author Rudon[285744011@qq.com]
 * 
 */
function createZip($from, $to) {
    /* Init */
    $return = array(
        'success' => false,
        'message' => '',
        'data' => array(
            'zipFile' => array(
                'name' => '',
                'path_relative' => '',
                'path_absolute' => '',
                'url' => '', // 自己添加吧
                'size' => '',
                'exists_before' => false
            )
        )
    );
    /* Check zip class */
    if (!class_exists('ZipArchive')) {
        $return['message'] = 'Missing ZipArchive module in server.';
        return $return;
    }
    /* Check right of write for target zip file */
    $zip = new ZipArchive();
    if (!is_dir(dirname($to))) {
        mkdir(dirname($to), 0755, TRUE);
    }
    if (is_file($to)) {
        $return['data']['zipFile']['exists_before'] = true;
        if ($zip->open($to, ZIPARCHIVE::OVERWRITE) !== TRUE) {
            $return['message'] = "Cannot overwrite: {$to}";
            return $return;
        }
    } else {
        if ($zip->open($to, ZIPARCHIVE::CREATE) !== TRUE) {
            $return['message'] = "Could not create archive: {$to}";
            return $return;
        }
    }
    /* Check path of source files or folder */
    $source_path_including_dir = array();
    $prefix_relative_path_for_source = '';
    if (is_array($from)) {
        foreach ($from as $path) {
            if (file_exists($path)) {
                if ($prefix_relative_path_for_source == '') {
                    $prefix_relative_path_for_source = (is_dir($path)) ? realpath($path) : realpath(dirname($path));
                }
                $source_path_including_dir[] = $path;
            } else {
                $return['message'] = 'No such file or folder: ' . $path;
                return $return;
            }
        }
    } elseif (file_exists($from)) {
        $prefix_relative_path_for_source = (is_dir($from)) ? realpath($from) : realpath(dirname($from));
        $source_path_including_dir[] = $from;
    } else {
        $return['message'] = 'No such file or folder: ' . $from;
        return $return;
    }
    $prefix_relative_path_for_source = rtrim($prefix_relative_path_for_source, '/') . '/';
    /* Get final list of files, no folder */
    $final_list_of_files = array();
    foreach ($source_path_including_dir as $path) {
        if (is_file($path)) {
            /* File */
            $final_list_of_files[] = $path;
        } else {
            /* Folder */
            $list_of_files = recursive_get_files_by_path_of_folder($path);
            foreach ($list_of_files as $one) {
                $final_list_of_files[] = $one;
            }
        }
    }
    if (!count($final_list_of_files)) {
        $return['message'] = 'No valid file or folder used to zip';
        return $return;
    }
    /* Begin to add to zip file */
    foreach ($final_list_of_files as $one_file) {
        $zip->addFile($one_file, str_replace($prefix_relative_path_for_source, '', $one_file));
    }
    $zip->close();
    /* Return */
    $return['success'] = true;
    $return['data']['zipFile']['name'] = pathinfo($to, PATHINFO_BASENAME);
    $return['data']['zipFile']['path_relative'] = $to;
    $return['data']['zipFile']['path_absolute'] = realpath($to);
    $return['data']['zipFile']['size'] = number_format(abs(filesize($to) / 1024), 2) . ' KB';
    return $return;
} 
/**
 * 获取文件夹下的文件列表,遍历模式
 * 
 * @param type $dir
 * @param type $is_tree
 * @return string
 */
function recursive_get_files_by_path_of_folder($dir, $is_tree = false) {
    $files = array();
    $dir = preg_replace('/[\/]{1}$/i', '', $dir);
    if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            while (($file = readdir($handle)) !== false) {
                if ($file != "." && $file != "..") {
                    if (is_dir($dir . "/" . $file)) {
                        $sub_list = recursive_get_files_by_path_of_folder($dir . "/" . $file, $is_tree);
                        if ($is_tree) {
                            $files[$file] = $sub_list;
                        } else {
                            foreach ($sub_list as $one_sub_file) {
                                $files[] = $one_sub_file;
                            }
                        }
                    } else {
                        $files[] = $dir . "/" . $file;
                    }
                }
            }
            closedir($handle);
            return $files;
        }
    } else {
        $files[] = $dir;
        return $files;
    }
}
 
 
 
/************************************************
 * 参数$from的可选形式:
 * $from = array('A.php', 'B.php', 'C.php', './folderName/')
 * $from = './folderName/';
 * $from = 'xxx.txt';
 */
$from = 'layui';
$to ='backup/tmp-'.time().'.zip';
$zip_result = createZip($from, $to);
print_r($zip_result);
?>
Title - Artist
0:00