加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

如何在php生成的zip中排除文件

发布时间:2020-12-13 17:12:16 所属栏目:PHP教程 来源:网络整理
导读:我需要知道如何从php生成的zip中排除文件/文件夹.这是我的代码: public function archiveBackup($name = '',$source = '',$destination = '') { if (!extension_loaded('zip') || !file_exists($source)) { return false; } $zip = new ZipArchive(); if (!
我需要知道如何从php生成的zip中排除文件/文件夹.这是我的代码:

public function archiveBackup($name = '',$source = '',$destination = '') {
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }
    $zip = new ZipArchive();
    if (!$zip->open($destination.$name,ZIPARCHIVE::CREATE)) {
        return false;
    }
    $source = str_replace('','/',realpath($source));
    if (is_dir($source) === true) {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source),RecursiveIteratorIterator::SELF_FIRST);
        foreach ($files as $file) {
            $file = str_replace('',realpath($file));
            if(is_dir($file) === true) {
                $zip->addEmptyDir(str_replace($source . '/','',$file . '/'));
            }
            else if(is_file($file) === true) {
                $zip->addFromString(str_replace($source . '/',$file),file_get_contents($file));
            }       
        }
    }
    else if (is_file($source) === true) {
        $zip->addFromString(basename($source),file_get_contents($source));
    }
    $zip->close();
    return true;
}

示例:我需要排除文件夹“themes”和“style.css”文件,该怎么做?

解决方法

$exclude = array('themes','style.css');

    foreach ($files as $file) {
      if (!in_array($file,$exclude)) {
        $file = str_replace('',realpath($file));
        if(is_dir($file) === true) {
            $zip->addEmptyDir(str_replace($source . '/',$file . '/'));
        }
        else if(is_file($file) === true) {
            $zip->addFromString(str_replace($source . '/',file_get_contents($file));
        }
      }
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读