PHP 打包压缩目录或文件

技术文档 - PHP文档 作者: xcheng1986 发布于:2014-05-27 阅读(1864) (暂无评论)  

    /**
     * 打包压缩目录或文件
     * @return String 成功返回生成的文件名,错误返回false
     */
    public function packFile($source, $destination) {
        if (!extension_loaded('zip') || !file_exists($source)) {
            echo '[extension_loaded ZIP field ]' . "\r\n";
            return false;
        }
        $zip = new ZipArchive();
        if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
            echo '[open ' . $destination . ' field ]' . "\r\n";
            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 . '/'));
                } elseif (is_file($file) === true) {
                    $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
                }
            }
        } elseif (is_file($source) === true) {
            $zip->addFromString(basename($source), file_get_contents($source));
        }
        return $zip->close();
    }