function zipData($source, $destination) { if (extension_loaded('zip')) { if (file_exists($source)) { $zip = new ZipArchive(); if ($zip->open($destination, ZIPARCHIVE::CREATE)) { $source = realpath($source); if (is_dir($source)) { $iterator = new RecursiveDirectoryIterator($source); // skip dot files while iterating $iterator->setFlags(RecursiveDirectoryIterator::SKIP_DOTS); $files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { $file = realpath($file); if (is_dir($file)) { $zip->addEmptyDir(str_replace($source . '/', '', $file . '/')); } else { if (is_file($file)) { $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file)); } } } } else { if (is_file($source)) { $zip->addFromString(basename($source), file_get_contents($source)); } } } echo $destination . ' zip: successfully...'; echo "\n"; return $zip->close(); } } return false; }
public function writeToFile($filename) { @unlink($filename); //if the zip already exists, overwrite it $zip = new ZipArchive(); if (empty($this->sheets_meta)) { self::log("Error in " . __CLASS__ . "::" . __FUNCTION__ . ", no worksheets defined."); return; } if (!$zip->open($filename, ZipArchive::CREATE)) { self::log("Error in " . __CLASS__ . "::" . __FUNCTION__ . ", unable to create zip."); return; } $zip->addEmptyDir("docProps/"); $zip->addFromString("docProps/app.xml", self::buildAppXML()); $zip->addFromString("docProps/core.xml", self::buildCoreXML()); $zip->addEmptyDir("_rels/"); $zip->addFromString("_rels/.rels", self::buildRelationshipsXML()); $zip->addEmptyDir("xl/worksheets/"); foreach ($this->sheets_meta as $sheet_meta) { $zip->addFile($sheet_meta['filename'], "xl/worksheets/" . $sheet_meta['xmlname']); } if (!empty($this->shared_strings)) { $zip->addFile($this->writeSharedStringsXML(), "xl/sharedStrings.xml"); //$zip->addFromString("xl/sharedStrings.xml", self::buildSharedStringsXML() ); } $zip->addFromString("xl/workbook.xml", self::buildWorkbookXML()); $zip->addFile($this->writeStylesXML(), "xl/styles.xml"); //$zip->addFromString("xl/styles.xml" , self::buildStylesXML() ); $zip->addFromString("[Content_Types].xml", self::buildContentTypesXML()); $zip->addEmptyDir("xl/_rels/"); $zip->addFromString("xl/_rels/workbook.xml.rels", self::buildWorkbookRelsXML()); $zip->close(); }
/** * @param $folder * @param $zipFile * @param $exclusiveLength * @param $messager */ private static function folderToZip($folder, \ZipArchive &$zipFile, $exclusiveLength, callable $messager = null) { $handle = opendir($folder); while (false !== ($f = readdir($handle))) { if ($f != '.' && $f != '..') { $filePath = "{$folder}/{$f}"; // Remove prefix from file path before add to zip. $localPath = substr($filePath, $exclusiveLength); if (in_array($f, static::$ignoreFolders)) { continue; } elseif (in_array($localPath, static::$ignorePaths)) { $zipFile->addEmptyDir($f); continue; } if (is_file($filePath)) { $zipFile->addFile($filePath, $localPath); $messager && $messager(['type' => 'progress', 'percentage' => false, 'complete' => false]); } elseif (is_dir($filePath)) { // Add sub-directory. $zipFile->addEmptyDir($localPath); static::folderToZip($filePath, $zipFile, $exclusiveLength, $messager); } } } closedir($handle); }
function Zip($source, $destination){ if (extension_loaded('zip') === true) { if (file_exists($source) === true) { $zip = new ZipArchive(); if ($zip->open($destination, ZIPARCHIVE::CREATE) === true) { $source = realpath($source); if (is_dir($source) === true) { $zip->addEmptyDir('core/export/'); $zip->addEmptyDir('core/import/'); $zip->addEmptyDir('core/cache/'); $zip->addEmptyDir('archive/archives/'); $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { if (is_dir($file) === true && !strpos($file,'.') && !strpos($file,'/core/cache/')) { $zip->addEmptyDir(str_replace($source . '/', '', $file . '/')); } else if (is_file($file) === true && !strpos($file,'/core/cache/') && !strpos($file,'/archive/archives/')) { $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file)); } } } else if (is_file($source) === true) { $zip->addFromString(basename($source), file_get_contents($source)); } return $zip->close(); } } } return false; }
/** * 方法その1 * @param unknown $dir * @param unknown $file * @param string $root * @return boolean */ function zipDirectory($dir, $file, $root = "") { $zip = new ZipArchive(); $res = $zip->open($file, ZipArchive::CREATE); if ($res) { // $rootが指定されていればその名前のフォルダにファイルをまとめる if ($root != "") { $zip->addEmptyDir($root); $root .= DIRECTORY_SEPARATOR; } $baseLen = mb_strlen($dir); $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS | FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO), RecursiveIteratorIterator::SELF_FIRST); $list = array(); foreach ($iterator as $pathname => $info) { $localpath = $root . mb_substr($pathname, $baseLen); // debug($localpath); if ($info->isFile()) { // $zip->addFile($pathname,$filenameonly ); $zip->addFile($pathname, $localpath); } else { $res = $zip->addEmptyDir($localpath); } } $zip->close(); } else { return false; } }
/** * Zip files * * @param string $targetDir Target dir path * @param array $files Files to zip * * @throws \Exception */ private function zipFiles($targetDir, $files) { $zip = new \ZipArchive(); $zipName = pathinfo($files[0], PATHINFO_FILENAME); $zipPath = FileSystem::getUniquePath($targetDir . DIRECTORY_SEPARATOR . $zipName . ".zip"); if ($zip->open($zipPath, \ZipArchive::CREATE)) { foreach ($files as $file) { $path = $targetDir . DIRECTORY_SEPARATOR . $file; if (is_dir($path)) { $zip->addEmptyDir($file); foreach (Finder::find("*")->from($path) as $item) { $name = $file . DIRECTORY_SEPARATOR . substr_replace($item->getPathname(), "", 0, strlen($path) + 1); if ($item->isDir()) { $zip->addEmptyDir($name); } else { $zip->addFile($item->getRealPath(), $name); } } } else { $zip->addFile($path, $file); } } $zip->close(); } else { throw new \Exception("Can not create ZIP archive '{$zipPath}' from '{$targetDir}'."); } }
/** * Authors: http://stackoverflow.com/questions/1334613/how-to-recursively-zip-a-directory-in-php thx for that * @param $source * @param $destination * @param bool $include_dir * @param array $additionalIgnoreFiles * @return bool */ private function zipCreate($source, $destination, $include_dir = false, $additionalIgnoreFiles = array()) { // Ignore "." and ".." folders by default $defaultIgnoreFiles = array('.', '..'); // include more files to ignore $ignoreFiles = array_merge($defaultIgnoreFiles, $additionalIgnoreFiles); if (!extension_loaded('zip') || !file_exists($source)) { return false; } if (file_exists($destination)) { unlink($destination); } $zip = new \ZipArchive(); if (!$zip->open($destination, \ZIPARCHIVE::CREATE)) { return false; } $source = str_replace('\\', '/', realpath($source)); if (is_dir($source) === true) { $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST); if ($include_dir) { $arr = explode("/", $source); $maindir = $arr[count($arr) - 1]; $source = ""; for ($i = 0; $i < count($arr) - 1; $i++) { $source .= '/' . $arr[$i]; } $source = substr($source, 1); $zip->addEmptyDir($maindir); } foreach ($files as $file) { $file = str_replace('\\', '/', $file); // purposely ignore files that are irrelevant if (in_array(substr($file, strrpos($file, '/') + 1), $ignoreFiles)) { continue; } $file = 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; }
/** * * zip a directory or some file * @param String/Array $directoryORfilesarray * @return boolean * @throws Exception */ public function zip($directoryORfilesarray = '.') { //backup old zip file if (file_exists($this->zipName)) { if (!rename($this->zipName, $this->zipName . '.old')) { throw new Exception("Cannot backup {$this->zipName} File, check permissions!"); } } //create zip file if ($this->ZipArchive->open($this->zipName, ZIPARCHIVE::CREATE) !== TRUE) { throw new Exception("Cannot create {$this->zipName} File, check permissions and directory!"); } //zip a directory if (is_string($directoryORfilesarray) && is_dir($directoryORfilesarray)) { $dir = rtrim($directoryORfilesarray, '/'); //get all file $this->_getAllFiles($dir, $this->allFiles); //add file to zip file foreach ($this->allFiles as $file) { if (is_dir($file)) { if ($dir == '.') { $file = substr($file, 2); } $this->ZipArchive->addEmptyDir($file); } if (is_file($file)) { if ($dir == '.') { $file = substr($file, 2); } $this->ZipArchive->addFile($file); } } } //zip some files if (is_array($directoryORfilesarray)) { foreach ($directoryORfilesarray as $file) { if (!file_exists($file)) { throw new Exception("{$file} is not exists!"); } if (is_dir($file)) { $this->ZipArchive->addEmptyDir($file); } if (is_file($file)) { $this->ZipArchive->addFile($file); } } } return $this->ZipArchive->close(); }
function exportZip($fileName) { $queue = [['', $this->rootFolder]]; $zip = new ZipArchive(); $zip->open($fileName, ZIPARCHIVE::CREATE); if ($this->rootFolder->isProxy) { while ($queue) { list($path, $folder) = array_shift($queue); foreach ($folder->getItemArray() as $item) { if ($item instanceof Folder) { if ($path) { $subpath = "{$path}/{$item->name}"; } else { $subpath = $item->name; } $queue[] = [$subpath, $item]; $zip->addEmptyDir($subpath); } elseif ($item instanceof File) { if ($path) { $subpath = "{$path}/{$item->name}"; } else { $subpath = $item->name; } $content = $item->getContent(); $zip->addFromString($subpath, $content['content']); } } } } $zip->close(); }
/** * * @return boolean * @throws Kohana_Exception */ public function create() { if (!extension_loaded('zip') === true) { throw new Kohana_Exception('Extension "zip" not loaded'); } $zip = new ZipArchive(); if ($zip->open(BACKUP_PLUGIN_FOLDER . 'filesystem-' . date('YmdHis') . '.zip', ZIPARCHIVE::CREATE) === true) { $sources = array(PUBLICPATH, PLUGPATH, LAYOUTS_SYSPATH, SNIPPETS_SYSPATH); foreach ($sources as $source) { if (is_dir($source) === true) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { $file = realpath($file); if (is_dir($file) === true) { $zip->addEmptyDir(str_replace(DOCROOT, '', $file . DIRECTORY_SEPARATOR)); } else { if (is_file($file) === true) { $zip->addFromString(str_replace(DOCROOT, '', $file), file_get_contents($file)); } } } } } $zip->close(); return TRUE; } return FALSE; }
/** * Compresses a given folder to a ZIP file * * @param string $inputFolder the source folder that is to be zipped * @param string $zipOutputFile the destination file that the ZIP is to be written to * @return boolean whether this process was successful or not */ function zipFolder($inputFolder, $zipOutputFile) { if (!extension_loaded('zip') || !file_exists($inputFolder)) { return false; } $zip = new ZipArchive(); if (!$zip->open($zipOutputFile, ZIPARCHIVE::CREATE)) { return false; } $inputFolder = str_replace('\\', '/', realpath($inputFolder)); if (is_dir($inputFolder) === true) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($inputFolder, FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS), RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { $file = str_replace('\\', '/', $file); if (is_dir($file) === true) { $dirName = str_replace($inputFolder . '/', '', $file . '/'); $zip->addEmptyDir($dirName); } else { if (is_file($file) === true) { $fileName = str_replace($inputFolder . '/', '', $file); $zip->addFromString($fileName, file_get_contents($file)); } } } } else { if (is_file($inputFolder) === true) { $zip->addFromString(basename($inputFolder), file_get_contents($inputFolder)); } } return $zip->close(); }
/** * Zip Action * * @return bool */ public function zip() { $recursive = []; foreach ($this->files as $name => $file) { $realPath = $file->getRealPath(); //echo $name . '<br />'; $baseName = basename($name); if ($baseName == '..' || $baseName == '.') { $folder = trim($realPath, '.'); if ($this->checkNotContains($folder) == false) { $recursive[] = ['zFolder' => 1, 'fileRoot' => null, 'fileDes' => null, 'folder' => str_replace($this->baseDir, '', $folder)]; } } else { if ($realPath && $this->checkNotContains($realPath) == false) { $recursive[] = ['zFile' => 1, 'fileRoot' => $realPath, 'fileDes' => str_replace($this->baseDir, '', $realPath), 'folder' => null]; } } } $recursive = array_reverse($recursive); foreach ($recursive as $r) { if ($r['fileDes']) { $this->zip->addFile($r['fileRoot'], $r['fileDes']); } else { $this->zip->addEmptyDir($r['folder']); } } return $this->zip->close(); }
/** * Creates the distribution artifact. * * @param \Generator $emoteGenerator Contains a generator which will yield objects * of type GbsLogistics\Emotes\EmoteBundle\Entity\Emote . * @return ReleaseArtifact */ public function generateArtifact(\Generator $emoteGenerator) { $zipDir = $this->getNamespace(); $outputFilename = tempnam(sys_get_temp_dir(), $this->getNamespace()); $zip = new \ZipArchive(); if (!$zip->open($outputFilename)) { throw new \RuntimeException(sprintf('Can\'t open file %s for writing', $outputFilename)); } $zip->addEmptyDir($zipDir); $header = $this->generateHeader(); $themeFile = sprintf(<<<EOTXT Name=%s Description=%s Icon=%s Author=%s [default] EOTXT , $header->getName(), $header->getDescription(), $header->getIcon(), $header->getAuthor()); /** @var Emote $emote */ foreach ($emoteGenerator as $emote) { $themeFile .= $this->generateEmoteEntry($emote); $zip->addFile($this->dataStorage->getImageSourcePath($emote->getPath()), $zipDir . '/' . $emote->getPath()); } $zip->addFromString($zipDir . '/theme', $themeFile); $zip->close(); $artifact = new ReleaseArtifact(); $artifact->setNamespace($this->getNamespace()); $artifact->setPath($outputFilename); $artifact->setName($this->getName()); return $artifact; }
public static function zip($source, $destination, $exclude = '') { if (extension_loaded('zip') === true) { if (file_exists($source) === true) { $zip = new ZipArchive(); if ($zip->open($destination, ZIPARCHIVE::CREATE) === true) { $source = realpath($source); if (is_dir($source) === true) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { if (strpos($file, $exclude) == 0) { $file = realpath($file); if (is_dir($file) === true) { $zip->addEmptyDir(str_replace($source . DIRECTORY_SEPARATOR, '', $file . DIRECTORY_SEPARATOR)); } else { if (is_file($file) === true) { $zip->addFile($file, str_replace($source . DIRECTORY_SEPARATOR, '', $file)); } } } } } else { if (is_file($source) === true) { $zip->addFile($source, basename($source)); //$zip->addFromString(basename($source), file_get_contents($source)); } } } return $zip->close(); } } return false; }
/** * Creates a zip file from a file or a folder recursively without a full nested folder structure inside the zip file * Based on: http://stackoverflow.com/a/1334949/3073849 * @param string $source The path of the folder you want to zip * @param string $destination The path of the zip file you want to create * @return bool Returns TRUE on success or FALSE on failure. */ public static function zip($source, $destination) { if (!extension_loaded('zip') || !file_exists($source)) { return false; } $zip = new ZipArchive(); if (!$zip->open($destination, ZIPARCHIVE::CREATE)) { return false; } $source = str_replace('\\', '/', realpath($source)); if (is_dir($source)) { foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST) as $path) { $path = str_replace('\\', '/', $path); $path = realpath($path); if (is_dir($path)) { $zip->addEmptyDir(str_replace($source . '/', '', $path . '/')); } elseif (is_file($path)) { $zip->addFile($path, str_replace($source . '/', '', $path)); } } } elseif (is_file($source)) { $zip->addFile($source, basename($source)); } return $zip->close(); }
/** * Adds a folder to the archive * @param string $path The folder which will be copied into the archive * @param string $name The entry name * @return $this * @throws */ public function addFolder($path, $name = null) { $fs = new Filesystem(); //check the folder exists if (!is_dir($path)) { throw new \InvalidArgumentException("Folder \"{$path}\" not found."); } $path = rtrim($path, '\\//'); //set the default name if (is_null($name)) { $name = basename($path); if ($name == '.') { $name = basename(dirname($path)); } } // @see http://us.php.net/manual/en/ziparchive.addfile.php#89813 // @see http://stackoverflow.com/questions/4620205/php-ziparchive-corrupt-in-windows $name = str_replace('\\', '/', ltrim($name, '\\/')); if (!empty($name) && $this->archive->statName($name) === false) { if ($this->archive->addEmptyDir($name) === false) { throw new \RuntimeException("Unable to add folder \"{$path}\" to ZIP archive as \"{$name}\"."); } } //** I had to use \DirectoryIterator instead of \deit\filesystem\Finder because I kept hitting the directory not empty when trying to remove files after this method $it = new \FilesystemIterator($path); foreach ($it as $p) { if (empty($name)) { $n = $fs->getRelativePath($p->getPathname(), $path); } else { $n = $name . '/' . $fs->getRelativePath($p->getPathname(), $path); } $this->add($p->getPathname(), $n); } return $this; }
public static function zip($source) { if (!extension_loaded('zip') || !file_exists($source)) { return false; } $zippedfile = uniqid(sys_get_temp_dir() . "/") . ".zip"; $zip = new ZipArchive(); if (!$zip->open($zippedfile, ZIPARCHIVE::CREATE)) { return false; } if (is_dir($source) === true) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { // Ignore "." and ".." folders if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) { continue; } 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 $zippedfile; }
private function addFilesIntoArchive(Tracker_Artifact_ChangesetValue_File $value, ZipArchive $archive) { $archive->addEmptyDir(self::DATA_DIR); foreach ($value->getFiles() as $file_info) { $archive->addFile($file_info->getPath(), self::DATA_DIR . DIRECTORY_SEPARATOR . self::FILE_PREFIX . $file_info->getId()); } }
public static function zip($source, $destination) { if (!extension_loaded('zip') || !file_exists($source)) { return false; } $zip = new \ZipArchive(); if (!$zip->open($destination, \ZIPARCHIVE::CREATE)) { return false; } $source = str_replace('\\', '/', realpath($source)); $parent = pathinfo($source, PATHINFO_DIRNAME); if (is_dir($source)) { $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { $file = str_replace('\\', '/', realpath($file)); if (is_dir($file)) { if ($file != $parent) { $zip->addEmptyDir(str_replace($source . '/', '', $file . '/')); } } elseif (is_file($file)) { $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file)); } } } elseif (is_file($source)) { $zip->addFromString(basename($source), file_get_contents($source)); } return $zip->close(); }
function Zip($source, $destination) { if (!extension_loaded('zip') || !file_exists($source)) { return false; } $zip = new ZipArchive(); if (!$zip->open($destination, 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)); } } return $zip->close(); }
/** * Creates the distribution artifact. * * @param \Generator $emoteGenerator Contains a generator which will yield objects * of type GbsLogistics\Emotes\EmoteBundle\Entity\Emote . * @return ReleaseArtifact */ public function generateArtifact(\Generator $emoteGenerator) { $zipDir = 'GoonfleetEmotes.AdiumEmoticonSet'; $outputFilename = tempnam(sys_get_temp_dir(), $this->getNamespace()); $zip = new \ZipArchive(); if (!$zip->open($outputFilename)) { throw new \RuntimeException(sprintf('Can\'t open file %s for writing', $outputFilename)); } $zip->addEmptyDir($zipDir); $plist = <<<PLISTHEADER <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>AdiumSetVersion</key> <integer>1</integer> <key>Emoticons</key> <dict> PLISTHEADER; foreach ($emoteGenerator as $emote) { $plist .= $this->getPlistEntry($emote); $zip->addFile($this->dataStorage->getImageSourcePath($emote->getPath()), $zipDir . '/' . $emote->getPath()); } $plist .= '</dict></dict></plist>'; $zip->addFromString($zipDir . '/Emoticons.plist', $plist); $zip->close(); $artifact = new ReleaseArtifact(); $artifact->setNamespace($this->getNamespace()); $artifact->setPath($outputFilename); $artifact->setName($this->getNamespace()); return $artifact; }
/** * @param InputInterface $input * @param OutputInterface $output * @return int|null|void * @throws \RuntimeException */ protected function execute(InputInterface $input, OutputInterface $output) { $commandConfig = $this->getCommandConfig(); $this->detectMagento($output); $finder = new Finder(); $finder->files()->followLinks(true)->in($this->getApplication()->getMagentoRootFolder() . DIRECTORY_SEPARATOR . 'media'); if ($input->getOption('strip')) { $finder->exclude($commandConfig['strip']['folders']); } $filename = (string) $input->getArgument('filename'); if (is_dir($filename)) { // support for dot dir $filename = realpath($filename); $filename .= '/'; } if (empty($filename) || is_dir($filename)) { $filename .= 'media_' . date('Ymd_his') . '.zip'; } $zip = new \ZipArchive(); $zip->open($filename, \ZIPARCHIVE::CREATE); $zip->addEmptyDir('media'); $lastFolder = ''; foreach ($finder as $file) { /* @var $file SplFileInfo */ $currentFolder = pathinfo($file->getRelativePathname(), PATHINFO_DIRNAME); if ($currentFolder != $lastFolder) { $output->writeln(sprintf('<info>Compress directory:</info> <comment>media/%s</comment>', $currentFolder)); } $zip->addFile($file->getPathname(), 'media' . DIRECTORY_SEPARATOR . $file->getRelativePathname()); $lastFolder = $currentFolder; } $zip->close(); }
protected function execute(InputInterface $input, OutputInterface $output) { $output->getFormatter()->setStyle('red', new OutputFormatterStyle('red')); $output->getFormatter()->setStyle('cyan', new OutputFormatterStyle('cyan')); $output->getFormatter()->setStyle('green', new OutputFormatterStyle('green')); $output->getFormatter()->setStyle('magenta', new OutputFormatterStyle('magenta')); $this->progress = new ProgressBar($output); $this->progress->setFormat('Archiving <cyan>%current%</cyan> files [<green>%bar%</green>] %elapsed:6s% %memory:6s%'); $name = basename($this->source); $dir = dirname($this->source); $date = date('YmdHis', time()); $filename = $name . '-' . $date . '.zip'; $destination = $input->getArgument('destination') ? $input->getArgument('destination') : ROOT_DIR; $destination = rtrim($destination, DS) . DS . $filename; $output->writeln(''); $output->writeln('Creating new Backup "' . $destination . '"'); $this->progress->start(); $zip = new \ZipArchive(); $zip->open($destination, \ZipArchive::CREATE); $zip->addEmptyDir($name); $this->folderToZip($this->source, $zip, strlen($dir . DS), $this->progress); $zip->close(); $this->progress->finish(); $output->writeln(''); $output->writeln(''); }
/** * Adds file or directory to archive * * @param string $source * @param string $destination * * @return bool * * @throws \Exception */ public function archive($source, $destination) { if (!file_exists($source)) { throw new \Exception('File or directory not found'); } $zip = new \ZipArchive(); if (!$zip->open($destination, \ZIPARCHIVE::OVERWRITE)) { throw new \Exception('Unable to open zip archive'); } $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('\\', '/', $file); // Ignore "." and ".." folders if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) { continue; } $file = realpath($file); $file = str_replace('\\', '/', $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, FILE_BINARY)); } } } } else { if (is_file($source) === true) { $zip->addFromString(basename($source), file_get_contents($source, FILE_BINARY)); } } return $zip->close(); }
function zipFile($source, $destination, $flag = '') { if (!extension_loaded('zip') || !file_exists($source)) { return false; } $zip = new ZipArchive(); if (!$zip->open($destination, ZIPARCHIVE::CREATE)) { return false; } $source = str_replace('\\', '/', realpath($source)); if ($flag) { $flag = basename($source) . '/'; //$zip->addEmptyDir(basename($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 . '/', '', $flag . $file . '/')); } else { if (is_file($file) === true) { $zip->addFromString(str_replace($source . '/', '', $flag . $file), file_get_contents($file)); } } } } else { if (is_file($source) === true) { $zip->addFromString($flag . basename($source), file_get_contents($source)); } } echo "Successfully Ziped Folder"; header('Location:admin/dashboard/admin_dashboard'); return $zip->close(); }
private function CreateExportArchive($strTranslationPath, $strArchive) { if (file_exists($strArchive)) { unlink($strArchive); } $arrFiles = NarroUtils::ListDirectory($strTranslationPath, null, null, null, true); $objZipFile = new ZipArchive(); if ($objZipFile->open($strArchive, ZipArchive::OVERWRITE) === TRUE) { foreach ($arrFiles as $strFileName) { if ($strTranslationPath == $strFileName) { continue; } if (is_dir($strFileName)) { $objZipFile->addEmptyDir(str_replace($strTranslationPath . '/', '', $strFileName)); } elseif (is_file($strFileName)) { $objZipFile->addFile($strFileName, str_replace($strTranslationPath . '/', '', $strFileName)); } } } else { NarroLogger::LogError(sprintf('Failed to create a new archive %s', $strArchive)); return false; } $objZipFile->close(); if (file_exists($strArchive)) { chmod($strArchive, 0666); } else { NarroLogger::LogError(sprintf('Failed to create an archive %s', $strArchive)); return false; } return true; }
/** * @param int $destination Target path of the zip, if you do not want to use $this->_targetPath * @return void */ public function zip($destination = null) { $source = $this->_workingDir; if (!$destination) { $destination = $this->_targetPath; } $this->_preZipChecks(); $zip = new ZipArchive(); if (!$zip->open($destination, ZIPARCHIVE::CREATE)) { throw new Exception("Could not open a new zip archive at {$destination}."); } $source = str_replace('\\', '/', realpath($source)); if (is_dir($source) === true) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::LEAVES_ONLY); foreach ($files as $file) { $file = str_replace('\\', '/', $file); // Ignore "." and ".." folders if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) { continue; } $file = 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)); } $zip->close(); }
public function backup() { if (!class_exists('ZipArchive')) { return false; } $zip = new \ZipArchive(); // Attempt to create the zip file. if ($zip->open($this->get_backup_filepath(), \ZIPARCHIVE::CREATE)) { foreach ($this->get_files() as $file) { // Create an empty directory for each directory in the filesystem if ($file->isDir()) { $zip->addEmptyDir($file->getRelativePathname()); } elseif ($file->isFile()) { $zip->addFile($file->getPathname(), $file->getRelativePathname()); } } // Track any internal warnings if ($zip->status) { $this->warning(__CLASS__, $zip->status); } if ($zip->statusSys) { $this->warning(__CLASS__, $zip->statusSys); } $zip->close(); } return $this->verify_backup(); }
public function Zip($source, $destination, $overwrite = false) { if (!extension_loaded('zip') || !file_exists($source)) { return false; } $zip = new ZipArchive(); if (!$zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : 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('\\', '/', $file); // Ignore "." and ".." folders if (in_array(substr($file, strrpos($file, '/') + 1), array('.', '..'))) { continue; } $file = 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)); } } return $zip->close(); }
public function create_zip($facility_code) { $this->update_rollout_status($facility_code); $this->create_core_tables($facility_code); $this->create_bat($facility_code); $sql_filepath = 'tmp/' . $facility_code . '.sql'; $expected_zip_sql_filepath = $facility_code . '/' . $facility_code . '.sql'; $bat_filepath = 'tmp/' . $facility_code . '_install_db.bat'; $expected_zip_bat_filepath = $facility_code . '/' . $facility_code . '_install_db.bat'; $ini_filepath = 'offline/my.ini'; $expected_ini_filepath = $facility_code . '/' . 'my.ini'; $expected_old_filepath = $facility_code . '/old/'; $zip = new ZipArchive(); $zip_name = $facility_code . '.zip'; $zip->open($zip_name, ZipArchive::CREATE); $zip->addFile($sql_filepath, ltrim($expected_zip_sql_filepath, '/')); $zip->addFile($bat_filepath, ltrim($expected_zip_bat_filepath, '/')); $zip->addEmptyDir($expected_old_filepath); $zip->addFile($ini_filepath, ltrim($expected_ini_filepath, '/')); $zip->close(); // ob_end_clean(); header("Cache-Control: public"); header("Content-Description: File Transfer"); // header("Content-Length: ". filesize("$zip_name").";"); header("Content-Disposition: attachment; filename={$zip_name}"); header("Content-type: application/zip"); header("Content-Transfer-Encoding: binary"); readfile($zip_name); unlink($sql_filepath); unlink($bat_filepath); unlink($zip_name); // echo "$final_output_bat"; // echo "I worked"; // echo "Expecto patronum"; }