分类 php_function 下的文章

压缩文件夹

因为打算使用php打包目录, 网上搜了搜现成的代码, 基本无用, 才写一下

<?php

function files($directory, &$fileList = [])
{
    $mydir = dir($directory);
    while ($file = $mydir->read()) {
        if ($file == "." || $file == "..") {
            continue;
        }
        if (is_dir("$directory/$file")) {
            files("$directory/$file", $fileList);
        } else {
            $fileList[] = $mydir->path . "/" . $file;
        }
    }
    $mydir->close();
    return $fileList;
}

function packageZip($dir, $savePath = null)
{
    if (!is_dir($dir)) {
        echo '<font style="color: red;">' . $dir . '不是一个目录</font>';
        return;
    }
    $savePath = empty($savePath) ? $dir . date("Y-m-d") . '.zip' : $savePath;
    $zip = new ZipArchive;
    is_file($savePath) ? unlink($savePath) : '';
    $res = $zip->open($savePath, ZipArchive::CREATE);
    if ($res === TRUE) {
        foreach (files($dir) as $item) {
            $zip->addFile($item);
        }
        $zip->close();
    }
}

packageZip('wuloves');