本文整理汇总了PHP中ZipArchive类的典型用法代码示例。如果您正苦于以下问题:PHP ZipArchive类的具体用法?PHP ZipArchive怎么用?PHP ZipArchive使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ZipArchive类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: save
/**
* 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
$sheetCount = $this->_spreadSheet->getSheetCount();
for ($i = 0; $i < $sheetCount; ++$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.");
}
}
示例2: Unzip
/**
* Uncompresses a ZIP archive to a given location.
* @author Bobby Allen (ballen@bobbyallen.me)
* @param string $archive Full path and filename to the ZIP archive.
* @param string $dest The full path to the folder to extract the archive into (with trailing slash!)
* @return boolean
*/
static function Unzip($archive, $dest)
{
global $zlo;
if (!class_exists('ZipArchive')) {
return false;
}
$zip = new ZipArchive();
$result = $zip->open($archive);
if ($result) {
if (@$zip->extractTo($dest)) {
$zip->close();
return true;
} else {
$zlo->logcode = "623";
$zlo->detail = "Unable to extract file '" . $archive . "' to '" . $dest . "'.";
$zlo->writeLog();
return false;
}
} else {
$zlo->logcode = "621";
$zlo->detail = "The archive file '" . $archive . "' appears to be invalid.";
$zlo->writeLog();
return false;
}
}
示例3: getMediaOutput
public static function getMediaOutput($id, $type, $className)
{
if ($type == 'list') {
$component = Kwf_Component_Data_Root::getInstance()->getComponentById($id);
if ($component) {
$galleryComponent = $component->parent;
$components = $galleryComponent->getChildComponents(array('generator' => 'child'));
$paths = array();
foreach ($components as $component) {
$data = $component->getComponent()->getImageData();
if ($data['file']) {
$paths[$data['file']] = $data['filename'];
}
}
}
if (!$paths) {
throw new Kwf_Exception_NotFound();
}
Kwf_Util_TempCleaner::clean();
$tmpname = "temp/" . uniqid() . ".zip";
$zip = new ZipArchive();
if ($zip->open($tmpname, ZIPARCHIVE::CREATE) !== TRUE) {
throw new Kwf_Exception('Could not open file for writing: ' . $filename);
}
foreach ($paths as $path => $filename) {
$zip->addFile($path, $filename);
}
$zip->close();
$file = array('file' => $tmpname, 'mimeType' => 'application/zip', 'downloadFilename' => $galleryComponent->getPage()->name . '.zip');
Kwf_Media_Output::output($file);
exit;
}
}
示例4: generate
/**
* Creates the new zip file based on the source_directory
*/
function generate()
{
$zip = new ZipArchive();
$zip->open($this->options['zip_temp_filename'], ZipArchive::CREATE && ZipArchive::OVERWRITE);
$source_path = realpath($this->options['source_directory']);
$iterator = new RecursiveDirectoryIterator($source_path);
foreach (new RecursiveIteratorIterator($iterator) as $filename) {
if (in_array(basename($filename), $this->options['exclude_files'])) {
continue;
}
foreach ($this->options['exclude_directories'] as $directory) {
if (strstr($filename, "/{$directory}/")) {
continue 2;
}
}
// continue the parent foreach loop
$zip_filepath = $filename->getRealPath();
$zip_filename = ltrim(str_replace($source_path, '', $zip_filepath), '\\');
$zip_filename = apply_filters("{$this->slug}_zip_generator_process_filename", $zip_filename);
$contents = $this->process_file_contents(file_get_contents($filename), basename($filename));
$zip->addFromString(trailingslashit($this->options['zip_root_directory']) . $zip_filename, $contents);
}
do_action("{$this->slug}_zip_generator_post_process", $zip, $this->options);
$zip->close();
}
示例5: testExportData
/**
* test export data
*/
public function testExportData() {
$dao = new BackupMySQLDAO();
$export_file = $dao->export();
$this->assertTrue( file_exists($export_file) );
$zip_stats = stat($export_file);
$this->assertTrue($zip_stats['size'] > 0);
$za = new ZipArchive();
$za->open($export_file);
$zip_files = array();
for ($i=0; $i<$za->numFiles;$i++) {
$zfile = $za->statIndex($i);
$zip_files[$zfile['name']] = $zfile['name'];
}
//verify we have create table file
$this->assertTrue($zip_files["create_tables.sql"]);
$za->close();
$q = "show tables";
$q2 = "show create table ";
$stmt = $this->pdo->query($q);
// verify we have all table files
while($data = $stmt->fetch(PDO::FETCH_ASSOC)) {
foreach($data as $key => $value) {
$zfile = '/' . $value .'.txt';
$this->assertTrue($zip_files[$zfile]);
}
}
}
示例6: fileValid
/**
* Validate file
*
* @param array $file
* @param int $max_file_size MB
* @param string $allowed_file_extension
* @return bool TRUE if valid ot FALSE if else
*/
public static function fileValid($file, $max_file_size, $allowed_file_extension)
{
// Dependencies test
if (!isset($file['tmp_name']) || !isset($file['name'])) {
return false;
} else {
if (empty($file['tmp_name']) || empty($file['name'])) {
return false;
} else {
// Common test
if (mb_strtolower($allowed_file_extension) != @pathinfo(self::_extensionPrepare($file['name']), PATHINFO_EXTENSION)) {
return false;
} else {
if ($max_file_size < @filesize($file['tmp_name']) / 1000000) {
return false;
}
}
// Extension test
if (mb_strtolower($allowed_file_extension) == 'zip') {
$zip = new ZipArchive();
if (true !== $zip->open($file['tmp_name'], ZipArchive::CHECKCONS)) {
$zip->close();
return false;
}
$zip->close();
}
}
}
return true;
}
示例7: actionIndex
/**
* 程序文件列表
*/
public function actionIndex()
{
if (isset($_POST['id'])) {
$files = $_POST['id'];
if ($files) {
//提交打包
$zip = new ZipArchive();
$name = 'yiifcmsBAK_' . date('YmdHis', time()) . '.zip';
$zipname = WWWPATH . '/' . $name;
//创建一个空的zip文件
if ($zip->open($zipname, ZipArchive::OVERWRITE)) {
foreach ((array) $files as $file) {
if (is_dir($file)) {
//递归检索文件
$allfiles = Helper::scanfDir($file, true);
foreach ((array) $allfiles['files'] as $v) {
$zip->addFile(WWWPATH . '/' . $v, $v);
}
} else {
$zip->addFile(WWWPATH . '/' . $file, $file);
}
}
$zip->close();
//开始下载
Yii::app()->request->sendFile($name, file_get_contents($zipname), '', false);
//下载完成后要进行删除
@unlink($zipname);
} else {
throw new CHttpException('404', 'Failed');
}
}
} else {
$files = Helper::scanfDir(WWWPATH);
asort($files['dirs']);
asort($files['files']);
$files = array_merge($files['dirs'], $files['files']);
$listfiles = array();
foreach ($files as $file) {
$tmpfilename = explode('/', $file);
$filename = end($tmpfilename);
if (is_dir($file)) {
$allfiles = Helper::scanfDir($file, true);
if ($allfiles['files']) {
$filesize = 0;
foreach ((array) $allfiles['files'] as $val) {
$filesize += filesize($val);
}
}
$listfiles[$filename]['type'] = 'dir';
} else {
$filesize = filesize($file);
$listfiles[$filename]['type'] = 'file';
}
$listfiles[$filename]['id'] = $filename;
$listfiles[$filename]['size'] = Helper::byteFormat($filesize);
$listfiles[$filename]['update_time'] = filemtime($filename);
}
}
$this->render('index', array('listfiles' => $listfiles));
}
示例8: export
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);
}
示例9: print_many_labels
function print_many_labels(&$params, &$parcels, $username)
{
require "config.php";
$return = array();
$zipname = "test_" . $username . '_' . session_id() . ".zip";
$zip = new ZipArchive();
$res = $zip->open($zipname, ZipArchive::CREATE);
if ($res === TRUE) {
$timestamp = date('dmy_His', time());
foreach ($parcels as $key => $parcel) {
$params['url'] = $base_url . 'reverselogistics/' . $parcel . '/label.json';
//echo json_encode($params);
$restApi2 = new RestApi($params);
$file_name = "InPost_Return_Label" . $timestamp . $key . ".pdf";
$pdf = $restApi2->getResponse();
$info = $restApi2->getInfo();
if ($info['http_code'] != 200) {
$_SESSION['error_message'] = 'Failed to create your labels ' . $info["http_code"];
continue;
}
$binary = base64_decode($pdf);
// Add to the list of parcels that need their status
// updated.
$return[] = $parcel;
// Add the PDF to the main ZIP file.
$zip->addFromString($file_name, $binary);
}
$zip->close();
} else {
$_SESSION['error_message'] = 'Failed to create ZIP file for your labels.';
header("Location: r_orders.php");
return $return;
}
return $return;
}
示例10: actionBulk
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');
}
示例11: copyDirToArchive
public static function copyDirToArchive($dir, $archive, $basename = null, $excludeDirs = null)
{
$dir = rtrim($dir, '/\\');
$basename = $basename ?: basename($dir);
rex_dir::create(dirname($archive));
$files = array();
$iterator = rex_finder::factory($dir)->recursive()->filesOnly();
if ($excludeDirs) {
$iterator->ignoreDirs($excludeDirs, false);
}
foreach ($iterator as $path => $file) {
$subpath = str_replace($dir, $basename, $path);
$subpath = str_replace('\\', '/', $subpath);
$files[$subpath] = $path;
}
if (class_exists('ZipArchive')) {
$zip = new ZipArchive();
$zip->open($archive, ZipArchive::CREATE);
foreach ($files as $path => $realpath) {
$zip->addFile($realpath, $path);
}
$zip->close();
} else {
$phar = new PharData($archive, 0, null, Phar::ZIP);
$phar->buildFromIterator(new ArrayIterator($files));
$phar->compressFiles(Phar::GZ);
foreach ($files as $path => $realpath) {
if (filesize($realpath) == 0) {
$phar[$path]->decompress();
}
}
}
}
示例12: process
/**
* Process job
*
* @param Job $job
* @return Job $job
*/
public function process(Job $job)
{
if (!class_exists('\\ZipArchive')) {
throw new \Exception('Zip extension is missing');
}
$zipFile = $job->getDocumentPath() . '/documents.zip';
if (file_exists($zipFile)) {
@unlink($zipFile);
}
$zip = new \ZipArchive();
if ($zip->open($zipFile, \ZipArchive::CREATE) !== TRUE) {
throw new \Exception('Couldn\'t create zip archive');
}
foreach ($job->getOutputDocuments() as $document) {
$zip->addFile($document->path, str_replace($job->getDocumentPath() . '/', '', $document->path));
}
$zip->close();
$documentDAO = $this->sm->get('Manager\\Model\\DAO\\DocumentDAO');
$docxDocument = $documentDAO->getInstance();
$docxDocument->path = $zipFile;
$docxDocument->job = $job;
$docxDocument->conversionStage = JOB_CONVERSION_STAGE_ZIP;
$job->documents[] = $docxDocument;
$job->conversionStage = JOB_CONVERSION_STAGE_ZIP;
return $job;
}
示例13: unzip
/**
* Unzip a file into the specified directory. Throws a RuntimeException
* if the extraction failed.
*/
public static function unzip($source, $base = null)
{
$base = $base ? $base : self::$folder;
@ini_set('memory_limit', '256M');
if (!is_dir($base)) {
mkdir($base);
chmod($base, 0777);
}
if (class_exists('ZipArchive')) {
// use ZipArchive
$zip = new ZipArchive();
$res = $zip->open($source);
if ($res === true) {
$zip->extractTo($base);
$zip->close();
} else {
throw new RuntimeException('Could not open zip file [ZipArchive].');
}
} else {
// use PclZip
$zip = new PclZip($source);
if ($zip->extract(PCLZIP_OPT_PATH, $base) === 0) {
throw new RuntimeException('Could not extract zip file [PclZip].');
}
}
return true;
}
示例14: route_makeRequest
public function route_makeRequest()
{
$type = pluralize(strip_tags($_GET['type']));
set_time_limit(0);
$fp = fopen("../{$type}/latest.zip", 'w+');
$url = str_replace(" ", "%20", strip_tags($_GET['url']));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
# write curl response to file
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);
$zip = new ZipArchive();
if ($zip->open("../{$type}/latest.zip") == true) {
mkdir("../{$type}/latest", 0777);
$zip->extractTo("../{$type}/latest");
$zip->close();
$handle = opendir("../{$type}/latest");
if ($handle) {
while (($file = readdir($handle)) !== false) {
if (is_dir("../{$type}/latest/{$file}")) {
if ($file != '.' and $file != '..') {
rename("../{$type}/latest/{$file}", "../{$type}/{$file}");
}
}
}
}
$this->rrmdir("../{$type}/latest");
unlink("../{$type}/latest.zip");
$this->rrmdir("../{$type}/__MACOSX");
}
Flash::notice(__("Extension downloaded successfully.", "extension_manager"), "/admin/?action=extend_manager");
}
示例15: execute
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('');
}