how to download Zip file to browser - php

I am trying to download some images as a zip file to my download folder in pc. But it always downloaded to the projects public folder. What can be the issue?
Here is my code
$photos = json_decode(Input::get('photos'));
$dir = time();
foreach($photos as $file){
$imgName = last(explode('/', $file));
$path = public_path('downloads/'.$dir);
if(!File::exists($path)){
File::makeDirectory($path, 0775, true);
}
ImageHandler::downloadFile($file, $path.'/'.$imgName);
}
$rootPath = realpath($path);
$zip = new ZipArchive();
$file_name = 'photos.zip';
$zip->open( $file_name, ZipArchive::CREATE | ZipArchive::OVERWRITE);
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file1)
{
// Skip directories (they would be added automatically)
if (!$file1->isDir())
{
// Get real and relative path for current file
$filePath = $file1->getRealPath();
$relativePath = substr($filePath, strlen($rootPath));
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");
readfile($filePath);
exit;

Related

why does the zip folder is not created with PHP

I'm trying to make a existing folder to a zip and download it using php. The existing folder contain some files. This is my code
$folder = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.']';
$zip_name = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.'].zip';
$zip = new ZipArchive;
if($zip -> open($zip_name, ZipArchive::CREATE ) === TRUE) {
$dir = opendir($folder);
while($file = readdir($dir)) {
if(is_file($folder.$file)) {
$zip -> addFile($folder.$file, $file);
}
}
$zip ->close();
}
But when i called the API zip folder is not created. Please go through my code and help me to solve it. Thanks in advance
// Get real path for our folder
$rootPath = realpath('folder-to-zip');
// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
Try below code.
$folder = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.']';
$zip_name = 'excel/report/[line: '.$args_line.'][startDate: '.$start_date.'][endDate: '.$end_date.'].zip';
$zip = new ZipArchive;
$zip->open($zip_name, ZipArchive::CREATE);
foreach (glob($folder) as $file) {
$zip->addFile($file);
}
$zip->close();

PHP creating zip archive adds local disk

I want to export all my images in a zip, but for some reason it adds all of my local disk too... I dont understand..
This is the code:
$files = $urls;
$zipname = 'uploads.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$name = explode( '/', $file);
$zip->addFile($file, pathinfo( $file, PATHINFO_BASENAME ));
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
$files is an array of the location of the image:
ServicesController.php on line 61:
array:3 [▼
0 => "C:\wamp\www\prjct\app/../../prjct/web/uploads/media/default/0001/15/thumb_14794_default_big.gif"
1 => "C:\wamp\www\prjct\app/../../prjct/web/uploads/media/default/0001/15/thumb_14794_default_small.gif"
2 => "C:\wamp\www\prjct\app/../../prjct/web/uploads/media/default/0001/15/thumb_14794_admin.gif"
]
When I opne my zip file i see this:
As you can see there is my local disk witch should not be here..
This should work:
$files = $urls;
$zipname = 'uploads.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
$rootPath = realpath($files);
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file) {
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// non-empty directories would be added automatically
if (!$file->isDir()){
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
$zip->close();
Generally, you should to use DIRECTORY_SEPARATOR predefined constant instead of slashes/back slashes. This is especially helpful when developing on a Windows machine.
Generally, when working on Windows, make sure to remove the trailing slash when adding folders to zip - that is what created the local disk in your zip file.
$localDirNoSlashes = rtrim($localDir, DIRECTORY_SEPARATOR);
$zip->addEmptyDir($localDirNoSlashes);
This was driving me crazy for a while until I realized what is going on...

Zipping random files in PHP

Hi I am trying to collect a number of random files from a folder on my server (./uploads) and zip them so the user can download. I think I am pretty close but I could use some help. I am getting a "503 backend fetch" error everytime and i can not pinpoint my issue. Thank you!!!
<?php
$rootPath = realpath('./uploads');
//make zip file
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
$nfiles = glob($rootPath.'*.{aiff}', GLOB_BRACE);
$files = $nfiles[array_rand($nfiles,20)];
//-------------------------------------------//
foreach ($files as $file)
{
if (!$file->isDir())
{
// Get path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add file to zip
$zip->addFile($filePath, $relativePath);
}
}
//-------------------------------------------//
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.'generated
sounds.zip');
header('Content-Length: ' . filesize('file.zip'));
readfile('file.zip');
if(file_exists('file.zip')){
unlink('file.zip');
}
?>

How to exclude folder(s) from ZIP file generation using php?

I found a great solution on how to ZIP folders and files on my server, but how do I make the script exclude the folder /archiv and all of its subfolders?
$backup_file = $_SERVER['DOCUMENT_ROOT'].'/archiv/system/system_' . date("Y-m-d-H-i-s") . '.zip';
$zip = new ZipArchive();
$zip->open($backup_file, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($_SERVER['DOCUMENT_ROOT']),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
if($file == 'archiv'){
continue;
}else{
// Skip directories (they would be added automatically)
if (!$file->isDir()){
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
$zip->addFile($filePath, $relativePath);
}
}
}
$zip->close();
Many thanks for any help!

How to create Zip file and download in CakePhp?

I'm trying to create zip files using CakePhp 1.3. The file descriptions are stored in database. In my controller I'm using the following logic.
// Fetching File description form database.
$this->view = 'Media';
$user_id=$this->Session->read('userData.User.id');
$condition = "Document.isdeleted = '0' AND Document.project_id='". $project_id."'";
$projectDocumentList = $this->Document->find("all",array('conditions'=>$condition,'fields'=>array('Document.id','Document.document_name','Document.path'),'order' => array('Document.id ASC')));
$this->set('projectDocumentList',$projectDocumentList);
if(!empty($projectDocumentList)){
$fileNames = "";
$fileNamesArr = array();
foreach($projectDocumentList as $projectDocument){
$fileNamesArr[ ]= $projectDocument['Document']['document_name'];
}
}
// Making zip
$archive_file_name='myFile.zip';
$file_path= "my_file_path";// Here I'm using my server basepath
$zip = new ZipArchive();
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
foreach($fileNamesArr as $files)
{
$zip->addFile($file_path.$files,$files);
//echo $file_path.$files."<br>"; // This can show the file in browser
}
$zip->close();
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
exit;
Now the zip file download as myFile.zip, but when I'm going to open that file, it throws an error "The archive is either in unknown format or damaged".
Create Zip File of whole folder
// Get real path for our folder
$rootPath = realpath('folder-to-zip');
// Initialize archive object
$zip = new ZipArchive();
$zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** #var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
And than pass the path of the zip file to the view.
$this->set('Zip_path'.zip_file_name);

Categories