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; }
/** * @inheritDoc */ public static function create(Request $request, $directory) { $order = $request->getOrder(); // Create the filename based on the order name. $zipFilePath = sprintf('%s/%s.zip', rtrim(rtrim($directory), '/'), $order->getOrderName()); // Create a new ZipFile on disk. $zip = new \ZipArchive(); $zip->open($zipFilePath, \ZipArchive::CREATE); // Add the order to the archive as an xml file. $encoder = new XmlEncoder(); $zip->addFromString('order.xml', $encoder->encode($order)); // Add the files to the archive. foreach ($request->getFiles() as $fileName => $filePath) { $zip->addFile($filePath, 'Input/' . $fileName); } // Add the content to the archive. foreach ($request->getContent() as $fileName => $content) { $zip->addFromString('Input/' . $fileName, $content); } // Close the file so the content gets compressed and the file is saved. $result = $zip->close(); // Check if no errors. if ($result !== true || !file_exists($zipFilePath)) { throw new FileException(sprintf('Can\'t create the zip archive "%s"', $zipFilePath)); } return new static($zipFilePath); }
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; }
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(); }
function Zip($source, $destination) { // Função que cira o arquivo zip a partir do diretorio informado $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('\\', '/', $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(); }
/** * Save PHPExcel to file * * @param string $pFileName * @throws Exception */ public function save($pFilename = null) { if (!is_null($this->_spreadSheet)) { // Garbage collect... foreach ($this->_spreadSheet->getAllSheets() as $sheet) { $sheet->garbageCollect(); } // Create new ZIP file and open it for writing $objZip = new ZipArchive(); // Try opening the ZIP file if ($objZip->open($pFilename, ZIPARCHIVE::OVERWRITE) !== true) { if ($objZip->open($pFilename, ZIPARCHIVE::CREATE) !== true) { throw new Exception("Could not open " . $pFilename . " for writing."); } } // Add media for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); $i++) { for ($j = 0; $j < $this->_spreadSheet->getSheet($i)->getDrawingCollection()->count(); $j++) { if ($this->_spreadSheet->getSheet($i)->getDrawingCollection()->offsetGet($j) instanceof PHPExcel_Worksheet_BaseDrawing) { $imgTemp = $this->_spreadSheet->getSheet($i)->getDrawingCollection()->offsetGet($j); $objZip->addFromString('media/' . $imgTemp->getFilename(), file_get_contents($imgTemp->getPath())); } } } // Add phpexcel.xml to the document, which represents a PHP serialized PHPExcel object $objZip->addFromString('phpexcel.xml', $this->_writeSerialized($this->_spreadSheet, $pFilename)); // Close file if ($objZip->close() === false) { throw new Exception("Could not close zip file {$pFilename}."); } } else { throw new Exception("PHPExcel object unassigned."); } }
public static function zip($source, $destination) { ini_set('max_execution_time', 600); ini_set('memory_limit', '1024M'); if (file_exists($source)) { $zip = new ZipArchive(); if ($zip->open($destination, ZIPARCHIVE::CREATE)) { $source = realpath($source); if (is_dir($source)) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), 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)); } } } else { throw new Exception("Could'nt open Destination ZIP File: {$destination}"); } return $zip->close(); } else { throw new Exception("source does not exists"); } return false; }
public function downloadAction() { $squadID = $this->params('id', 0); $squadRepo = $this->getEntityManager()->getRepository('Frontend\\Squads\\Entity\\Squad'); /** @var Squad $squadEntity */ $squadEntity = $squadRepo->findOneBy(array('user' => $this->identity(), 'id' => $squadID)); if (!$squadEntity) { $this->flashMessenger()->addErrorMessage('Squad not found'); return $this->redirect('frontend/user/squads'); } $fileName = 'squad_file_pack_armasquads_' . $squadID; $zipTmpPath = tempnam(ini_get('upload_tmp_dir'), $fileName); $zip = new \ZipArchive(); $zip->open($zipTmpPath, \ZipArchive::CHECKCONS); if (!$zip) { $this->flashMessenger()->addErrorMessage('Squad Package Download currently not possible'); return $this->redirect('frontend/user/squads'); } $zip->addFromString('squad.xml', file_get_contents('http://' . $_SERVER['SERVER_NAME'] . $this->url()->fromRoute('frontend/user/squads/xml', array('id' => $squadEntity->getPrivateID())))); if ($squadEntity->getSquadLogoPaa()) { $zip->addFile(ROOT_PATH . $squadEntity->getSquadLogoPaa(), basename($squadEntity->getSquadLogoPaa())); } $zip->addFromString('squad.dtd', file_get_contents(realpath(__DIR__ . '/../../../../view/squads/xml/') . '/squad.dtd')); //$zip->addFromString('squad.xsl',file_get_contents(realpath(__DIR__ . '/../../../../view/squads/xml/').'/squad.xsl')); $zip->close(); header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"" . basename($fileName) . ".zip\""); readfile($zipTmpPath); sleep(1); @unlink($zipTmpPath); die; }
/** * Save PhpPresentation to file * * @param string $pFilename * @throws \Exception */ public function save($pFilename) { if (empty($pFilename)) { throw new \Exception("Filename is empty."); } if (!is_null($this->presentation)) { // Create new ZIP file and open it for writing $objZip = new \ZipArchive(); // Try opening the ZIP file if ($objZip->open($pFilename, \ZipArchive::CREATE) !== true) { if ($objZip->open($pFilename, \ZipArchive::OVERWRITE) !== true) { throw new \Exception("Could not open " . $pFilename . " for writing."); } } // Add media $slideCount = $this->presentation->getSlideCount(); for ($i = 0; $i < $slideCount; ++$i) { for ($j = 0; $j < $this->presentation->getSlide($i)->getShapeCollection()->count(); ++$j) { if ($this->presentation->getSlide($i)->getShapeCollection()->offsetGet($j) instanceof AbstractDrawing) { $imgTemp = $this->presentation->getSlide($i)->getShapeCollection()->offsetGet($j); $objZip->addFromString('media/' . $imgTemp->getFilename(), file_get_contents($imgTemp->getPath())); } } } // Add PhpPresentation.xml to the document, which represents a PHP serialized PhpPresentation object $objZip->addFromString('PhpPresentation.xml', $this->writeSerialized($this->presentation, $pFilename)); // Close file if ($objZip->close() === false) { throw new \Exception("Could not close zip file {$pFilename}."); } } else { throw new \Exception("PhpPresentation object unassigned."); } }
/** * 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(); }
/** * ファイル追加(メモリ上から) * * @param string $binary 追加するファイルの内容 * @param string $filename zip 内でのファイル名 * @throws D9magai\Zip\Exception */ public function addString($filename, $binary) { $ret = $this->zipArchive->addFromString($filename, $binary); if ($ret !== true) { throw new Exception('ファイルの追加に失敗しました'); } }
function export($params = null) { $patients = $this->Patient->getPatients($params); unset($this->Patient); $zip = new ZipArchive(); $file = 'GaiaEHR-Patients-Export-' . time() . '.zip'; if ($zip->open($file, ZipArchive::CREATE) !== true) { throw new Exception("cannot open <{$file}>"); } $zip->addFromString('cda2.xsl', file_get_contents(ROOT . '/lib/CCRCDA/schema/cda2.xsl')); foreach ($patients as $i => $patient) { $patient = (object) $patient; $this->CCDDocument->setPid($patient->pid); $this->CCDDocument->createCCD(); $this->CCDDocument->setTemplate('toc'); $this->CCDDocument->createCCD(); $ccd = $this->CCDDocument->get(); $zip->addFromString($patient->pid . '-Patient-CDA' . '.xml', $ccd); unset($patients[$i], $ccd); } $zip->close(); header('Content-Type: application/zip'); header('Content-Length: ' . filesize($file)); header('Content-Disposition: attachment; filename="' . $file . '"'); readfile($file); }
/** * 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(); }
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(); }
/** * @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(); }
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; }
/** * Agrega un archivo al zip * @param nombre del archivo $nombre * @param ruta del archivo a comprimir $file */ public function add($nombre, $file) { if (is_file($file)) { # download file $download_file = file_get_contents($file); #add it to the zip $this->_zip->addFromString($nombre, $download_file); } }
/** * Zip a file, or entire directory recursively. * * @param string $source directory or file name * @param string $destinationPathAndFilename full path to output * @throws App_File_Zip_Exception * @return boolean whether zip was a success */ public static function CreateFromFilesystem($source, $destinationPathAndFilename) { $base = realpath(dirname($destinationPathAndFilename)); if (!is_writable($base)) { throw new App_File_Zip_Exception('Destination must be writable directory.'); } if (!is_dir($base)) { throw new App_File_Zip_Exception('Destination must be a writable directory.'); } if (!file_exists($source)) { throw new App_File_Zip_Exception('Source doesnt exist in location: ' . $source); } $source = realpath($source); if (!extension_loaded('zip') || !file_exists($source)) { return false; } $zip = new ZipArchive(); $zip->open($destinationPathAndFilename, ZipArchive::CREATE); if (is_dir($source) === true) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); $baseName = realpath($source); foreach ($files as $file) { if (in_array(substr($file, strrpos($file, DIRECTORY_SEPARATOR) + 1), array('.', '..'))) { continue; } $relative = substr($file, strlen($baseName)); if (is_dir($file) === true) { // Add directory $added = $zip->addEmptyDir(trim($relative, "\\/")); if (!$added) { throw new App_File_Zip_Exception('Unable to add directory named: ' . trim($relative, "\\/")); } } else { if (is_file($file) === true) { // Add file $added = $zip->addFromString(trim($relative, "\\/"), file_get_contents($file)); if (!$added) { throw new App_File_Zip_Exception('Unable to add file named: ' . trim($relative, "\\/")); } } } } } else { if (is_file($source) === true) { // Add file $added = $zip->addFromString(trim(basename($source), "\\/"), file_get_contents($source)); if (!$added) { throw new App_File_Zip_Exception('Unable to add file named: ' . trim($relative, "\\/")); } } else { throw new App_File_Zip_Exception('Source must be a directory or a file.'); } } $zip->setArchiveComment('Created with App_Framework'); return $zip->close(); }
/** * @return string */ public function finishAndGetDocument() { $content = $this->create(); $this->zip->deleteName('content.xml'); $this->zip->addFromString('content.xml', $content); $this->zip->close(); $content = file_get_contents($this->tmpZipFile); unlink($this->tmpZipFile); return $content; }
protected function setUp() { if (!extension_loaded('zip')) { $this->markTestSkipped('The zip extension is not available'); } $this->zipFile = new \ZipArchive(); $this->zipFile->open($this->zipFilename, \ZipArchive::CREATE); $this->zipFile->addFromString($this->filename, $this->fileContents); $this->zipFile->close(); $this->collection = new ResourceCollection([new FileResource(FileTransport::create($this->zipFilename))]); }
function action_exportrss() { //Bug 30094, If zlib is enabled, it can break the calls to header() due to output buffering. This will only work php5.2+ ini_set('zlib.output_compression', 'Off'); date_default_timezone_set("Asia/Shanghai"); $filename = "kittenrss_" . date("YmdHis"); ob_start(); $bean = BeanFactory::getBean('xeBayListings'); //$item_list = $bean->get_full_list("", "(listing_type='Chinese' OR listing_type='FixedPriceItem')"); $item_list = $bean->get_full_list(); if (count($item_list) == 0) { echo "Export RSS failed: No item"; ob_end_flush(); sugar_cleanup(true); } $tmpfname = tempnam(sys_get_temp_dir(), "kitten"); $zip = new ZipArchive(); $res = $zip->open($tmpfname, ZipArchive::CREATE); if ($res === TRUE) { foreach ($item_list as &$item) { // if (empty($item->item_id)) //continue; $rss = $item->build_shopwindow_topmost(true); if (!empty($rss)) { $zip->addFromString("rss/{$item->id}/head.xml", $rss); } $rss = $item->build_shopwindow_correlation(true); if (!empty($rss)) { $zip->addFromString("rss/{$item->id}/correlation.xml", $rss); } $rss = $item->build_shopwindow_random(true); if (!empty($rss)) { $zip->addFromString("rss/{$item->id}/random.xml", $rss); } } $zip->close(); $zipContent = file_get_contents($tmpfname); unlink($tmpfname); ob_clean(); header("Pragma: cache"); header('Content-Type: application/octet-stream'); header("Content-Disposition: attachment; filename={$filename}.zip"); header("Content-transfer-encoding: binary"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . TimeDate::httpTime()); header("Cache-Control: post-check=0, pre-check=0", false); header("Content-Length: " . strlen($zipContent)); print $zipContent; } else { echo 'Export RSS failed: Open zip file'; ob_end_flush(); } sugar_cleanup(true); }
/** * Saves file * * @param $filename * * @throws \Exception */ public function save($filename) { if (isset($this->contents)) { $this->zip->addFromString('word/document.xml', $this->contents); } $this->zip->close(); $res = @rename($this->tempFilename, $filename); if (!$res) { throw new \Exception("Unable to save file"); } }
/** * 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; }
function Zip($source, $destination) { if (!extension_loaded('zip') || !file_exists($source)) { echo 'Zip not loaded'; 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('\\', '/', $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) { $dirname = basename(dirname($file)); $extension = pathinfo($file, PATHINFO_EXTENSION); $filename = basename($file, '.' . $extension); // widgets/d3 && img/widgets select only checked widgets if ((strcmp($dirname, 'd3') == 0 or strcmp($dirname, 'widgets') == 0) and !in_array($filename, $_POST['widget']) or strcmp(basename($file), 'sefarad.html') == 0 or strcmp(basename($file), 'index.html') == 0) { continue; } if (strcmp(basename($file), 'index_copia.html') == 0) { $zip->addFromString('index.html', file_get_contents($file)); unlink($file); continue; } // if(strcmp(basename($file),'demo.html')==0){ // continue; // } $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 execute() { // return $this->exportInsiders(); // return $this->exportTravelers(); $insiders = $this->exportInsiders(); $travelers = $this->exportTravelers(); $zipName = "insider-traveler-list-" . date('Ymd-His') . ".zip"; $docRoot = $this->rootDir . '/../web/uploads/csv'; if (!is_writable($docRoot)) { mkdir("{$docRoot}", 0755); } $zipFile = $docRoot . "/" . $zipName; $zip = new \ZipArchive(); $zip->open($zipFile, \ZipArchive::CREATE); // $zip->addFile($insiders['file'],$insiders['file']); // $zip->addFile($travelers['file'],$travelers['file']); $zip->addFromString($insiders['filename'], file_get_contents($insiders['file'])); $zip->addFromString($travelers['filename'], file_get_contents($travelers['file'])); $zip->close(); return array("filename" => $zipName, "file" => $zipFile); // $localAuthors = $this->entityManager->getRepository('BugglMainBundle:LocalAuthor')->findBy( array('status' => $this->constants->get('allowed_user')) ); // $docRoot = $this->rootDir.'/../web/uploads/csv'; // if(!is_writable( $docRoot )){ // mkdir("$docRoot", 0755); // } // $filename = "local-author-list-" . date('Ymd-His') . ".csv"; // $file = $docRoot . "/" . $filename; // $FileHandle = fopen($file, 'w') or die("can't open file"); // fclose($FileHandle); // $fp = fopen($file, 'w'); // fputcsv( $fp, array("Name", "Email", "Link to Buggl Profile", "Registration Type") ); // foreach( $localAuthors as $iObj ) // { // $linkToProfile = $this->constants->get('site_url') . $this->router->generate( 'local_author_profile', array('slug' => $iObj->getSlug()) ); // $regType = ($iObj->getIsLocalAuthor()) ? "Travel Insider" : "Traveller"; // $authorInfo = array( // $iObj->getName(), // $iObj->getEmail(), // $linkToProfile, // $regType // ); // fputcsv( $fp, $authorInfo ); // } // fclose($fp); // return array( // "filename" => $filename, // "file" => $file // ); }
function wikiplugin_archivebuilder($data, $params) { if (!class_exists('ZipArchive')) { return '^' . tra('Missing ".zip" file name extension.') . '^'; } $archive = md5(serialize(array($data, $params))); if (isset($_POST[$archive])) { $files = array(); $handlers = array('tracker-attachments' => 'wikiplugin_archivebuilder_trackeratt', 'page-as-pdf' => 'wikiplugin_archivebuilder_pagetopdf'); $archive = new ZipArchive(); $archive->open($file = tempnam('temp/', 'archive') . '.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE); foreach (array_filter(explode("\n", trim($data))) as $line) { $parts = explode(":", trim($line)); $handler = array_shift($parts); if (isset($handlers[$handler])) { $result = call_user_func_array($handlers[$handler], $parts); foreach ($result as $name => $content) { $archive->addFromString($name, $content); $files[] = $name; } } else { return tra('Incorrect parameter') . ' ' . $handler; } } $archive->addFromString('manifest.txt', implode("\n", $files)); $archive->close(); // Compression of the stream may corrupt files on windows ob_end_clean(); ini_set('zlib.output_compression', 'Off'); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private", false); header('Content-Length: ' . filesize($file)); header('Content-Type: application/zip'); header('Content-Disposition: attachment; filename="' . $params['name'] . '";'); header('Connection: close'); header('Content-Transfer-Encoding: binary'); readfile($file); unlink($file); exit; } else { $label = tra('Download archive'); return <<<FORM <form method="post" action=""> \t<input type="submit" class="btn btn-default btn-sm" name="{$archive}" value="{$label}" /> </form> FORM; } }
/** * @test */ public function createZipArchive() { $zip = new ZipArchive(); $this->assertTrue($zip->open(vfsStream::url('root/test.zip'), ZIPARCHIVE::CREATE)); $this->assertTrue($zip->addFromString("testfile1.txt", "#1 This is a test string added as testfile1.txt.\n")); $this->assertTrue($zip->addFromString("testfile2.txt", "#2 This is a test string added as testfile2.txt.\n")); $zip->setArchiveComment('a test'); var_dump($zip); $this->assertTrue($zip->close()); var_dump($zip->getStatusString()); var_dump($zip->close()); var_dump($zip->getStatusString()); var_dump($zip); var_dump(file_exists(vfsStream::url('root/test.zip'))); }
public function actionBulk() { if (Yii::app()->request->isPostRequest) { $numOfItems = intval($_POST['numOfItems']); $archiveFileName = tempnam(sys_get_temp_dir(), uniqid()) . '.zip'; /*iterate n times*/ $templateGenerator = new TemplateGenerator(); $archiveFile = new ZipArchive(); $archiveFile->open($archiveFileName, ZipArchive::CREATE); foreach (range(1, $numOfItems) as $key => $value) { /*generate template*/ $template1 = $templateGenerator->generate(); /*put to archive*/ $archiveFile->addFromString(basename($template1), file_get_contents($template1)); } $archiveFile->close(); /*publish archive file*/ $publishedUrl = Yii::app()->assetManager->publish($archiveFileName); $messageoutput = CHtml::link('Download files', $publishedUrl); /*put link at flash*/ Yii::app()->user->setFlash("success", $messageoutput); /*redirect */ $this->redirect('/mainAccount/bulk'); /*done*/ } $this->render('//main_account/bulk'); }
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(); }