Following is my code to download zip file using PHP.
function create_zip($files, $file_name, $overwrite = false) {
foreach ($files as $imglink) {
$img = file_get_contents($imglink);
$destination_path = $_SERVER['DOCUMENT_ROOT'] . 'demoproject/downloads/' . time() . '.jpg';
file_put_contents($destination_path, $img);
$imgFiles[] = $destination_path;
}
if (file_exists($file_name) && !$overwrite) {
return false;
}
$valid_files = array();
if (is_array($imgFiles)) {
foreach ($imgFiles as $file) {
$valid_files[] = $file;
}
}
if (count($valid_files)) {
$zip = new ZipArchive();
if ($zip->open($file_name, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
echo "Sorry ZIP creation failed at this time";
}
foreach ($valid_files as $file) {
$zip->addFile($file, pathinfo($file, PATHINFO_BASENAME));
}
$count = $zip->numFiles;
$resultArr = array();
$resultArr['count'] = $count;
$resultArr['destination'] = $file_name;
$filename = $file_name;
$filepath = $_SERVER['DOCUMENT_ROOT'] . 'demoproject/';
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($filepath . $filename));
ob_end_flush();
#readfile($filepath . $filename);
} else {
return false;
}
}
Here the $filename and $filepath containing the name and path of zip file respectively.
Ex:
echo $filepath.$filename;
Output : D:/wamp/www/demoproject/1357198557.zip
The issue is it displaying download window but showing the folder size 0 byte. I am using windows7. See image below :
Can you try adding this, Make sure you got proper filesize
$mm_type="application/octet-stream";
header("Content-Type: " . $mm_type);
header("Content-Length: " .(string)(filesize($fullpath)) );
Related
Trying to create a zip-file with different pdf-files where I get the names on the pdf-files from checkboxes in a form.
I get the code to download a zip-file, but when I try to open it it say that
the zip is invalid. Sometimes I get no error but a empty folder. So it seems like $zip->addFile does not add the file.
Here is the code:
<?php
$test = $_POST['check'];
$zip = new ZipArchive;
if (!empty($_POST['check']))
{
$tmp_file = 'zip/myzip.zip';
if ($zip->open('myzip.zip') === TRUE)
{
foreach($_POST['check'] as $check)
{
$zip->addFile('pdf/' . $check, $check);
}
echo $tmp_file;
$zip->close();
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=\"" . $tmp_file . "\"");
header("Content-Transfer-Encoding: binary");
readfile($tmp_file);
ob_end_flush();
} else {
echo 'failed';
}
} else {
echo 'Ingen vald';
}
?>
I need to be able to open the zip file straight away when we hit the page for download even if the zip file is not created in the server yet.
Is there any way to do this? Because for the moment it takes a lot of time to get the page the start of the download of the zip file.
I'm also getting timeout issue because it takes too much time to build the zip.
$this->loadModel('JobFiles');
$this->loadComponent('Images');
$job_nbr = '40819-o';
$purpose = 'client';
if (isset($this->request->data['type']) && $this->request->data['type'] != '') {
$type = $this->request->data['type'];
$my_files = $this->JobFiles
->find()
->where([
'JobFiles.job_number' => $job_nbr,
'JobFiles.type' => $type,
'JobFiles.purpose' => $purpose
]);
} else {
$my_files = $this->JobFiles
->find()
->where([
'JobFiles.job_number' => $job_nbr,
'JobFiles.purpose' => $purpose
]);
}
$files = array();
$key = 0;
foreach( $my_files as $file ){
// If photo and extension are jpg we provide other files type
if ($file->type == 'photos' && $file->extension == 'jpg' || $file->extension == 'JPG'):
$c = $file->ObjectURL;
$file_headers = #get_headers($c);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$files['photos'][$key]['original_file'] = $file->ObjectURL;
$files['photos'][$key]['name'] = $file->filename;
$files['photos'][$key]['type'] = $file->type;
$files['photos'][$key]['id'] = $file->id;
$key++;
}
endif;
if ($file->type == 'floorplan'):
$files['floorplan'][$key]['original_file'] = $file->ObjectURL;
$key++;
endif;
if ($file->type == 'video'):
$files['video'][$key]['original_file'] = $file->ObjectURL;
$key++;
endif;
}
$zipname = "watherver.zip";
$zip = new ZipArchive();
$zip_full_path_name = \Cake\Core\Configure::read('pathTo') . '/webroot/img/tmp/zip/' . $zipname;
$zip->open($zip_full_path_name, ZIPARCHIVE::CREATE);
foreach ($files['photos'] as $file) {
$context = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
$parsed_file = $file['original_file'];
$download_file = file_get_contents($parsed_file, false,$context);
$zip->addFromString('photos/original/' . basename($parsed_file), $download_file);
}
$zip->close();
//Set headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename='" . $zipName . "'");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($zipName));
Cheers,
I'm trying to write code to zip a file and download it. My problem is when I download and open the file, I get the error
The archive is either in unknown format or damaged
Here's my code:
<?php
try{
$db_conn = new DBController();
$db_conn->prepare("SELECT filetypename FROM dirlistening WHERE dadroot = :BasName AND sonbas = :BasDirName");
$db_conn->bind(':BasName', $parentBasIndex);
$db_conn->bind(':BasDirName', $currentBas);
$db_conn->execute();
$dbzipoutput = $db_conn->getAll();
$db_conn->free();
$files = array();
if(!is_null($dbzipoutput)){
foreach($dbzipoutput as $azip){
$files[] = $azip->filetypename;
}
}
//$file_names = array("'" . implode( $filess, "','" ) . "'");
$file_names = $files;
function zipSourceFilesDownload($file_names,$archive_file_name,$file_path){
$zip = new ZipArchive();
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE){
exit("cannot open ".$archive_file_name."\n");
}else{
foreach($file_names as $filelist){
$zip->addFile($file_path.'/'.$filelist);
$zip->addEmptyDir($file_path.'/'.$filelist);
$zip->addFromString($file_path.'/'.$filelist, file_get_contents($file_path.'/'.$filelist));
$zip->setArchiveComment("zipped on ".date('Y-M-d')."
\nDownloaded from: My website
\nWebsite: http://www.example.com
\nProject Source: ".$file_path."
\nProject Url: http://example.com" . $_SERVER['REQUEST_URI']."
\nFILE COMMENT AND DESCRIPTION
\n none");
}
$var = $zip->close();
$download_file = true;
}
if($download_file){
ob_get_clean();
header("Pragma: no-cache");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/zip");
header('Content-disposition: attachment; filename='.$archive_file_name);
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($archive_file_name));
print $zip_file;
unlink($archive_name);
}
return $var;
}
zipSourceFilesDownload($file_names,$archive_file_name,$file_path);
}catch (PDOException $e){ echo 'Connection failed: ' . $e->getMessage();}
I've been working with this code all day but for some reason files won't get deleted after timer has run out.$zip_file_name is the file that I'd like to see gone after 30secs
$the_folder = '../test';
$zip_file_name = ("PHOENIX_fullbackup_$now.zip");
$download_file= true;
//$delete_file_after_download= true; doesnt work!!
class FlxZipArchive extends ZipArchive {
/** Add a Dir with Files and Subdirs to the archive;;;;; #param string $location Real Location;;;; #param string $name Name in Archive;;; #author Nicolas Heimann;;;; #access private **/
public function addDir($location, $name) {
$this->addEmptyDir($name);
$this->addDirDo($location, $name);
} // EO addDir;
/** Add Files & Dirs to archive;;;; #param string $location Real Location; #param string $name Name in Archive;;;;;; #author Nicolas Heimann
* #access private **/
private function addDirDo($location, $name) {
$name .= '/';
$location .= '/';
// Read all Files in Dir
$dir = opendir ($location);
while ($file = readdir($dir))
{
if ($file == '.' || $file == '..') continue;
// Rekursiv, If dir: FlxZipArchive::addDir(), else ::File();
$do = (filetype( $location . $file) == 'dir') ? 'addDir' : 'addFile';
$this->$do($location . $file, $name . $file);
}
} // EO addDirDo();
}
$za = new FlxZipArchive;
$res = $za->open($zip_file_name, ZipArchive::CREATE);
if($res === TRUE)
{
$za->addDir($the_folder, basename($the_folder));
$za->close();
}
else { echo 'Could not create a zip archive';}
if ($download_file)
{
ob_get_clean();
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . basename($zip_file_name) . ";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($zip_file_name));
readfile($zip_file_name);
if ($handle = opendir ($zip_file_name)) {
while (false !== ($file = readdir($handle))) {
if (filectime($file)< (time()-30)) { // timer -30secs
unlink($file);
}
}
}
}
?>
Any help is greatly appreciated.thanks
you could delete zip file (if it already exists) prior to generating the zip file - so that old files are deleted first before new ones are generated:
E.g. (snippet of your code)
<?php
// Delete previous zip files
$old_files = glob($the_folder .'/*.zip');
foreach ($old_files as $old_file) {
unlink($old_file);
}
// Usage
$za = new FlxZipArchive;
$res = $za->open($zip_file_name, ZipArchive::CREATE);
if ($res === TRUE)
{
// Add Files to Zip
$za->addDir($the_folder, basename($the_folder));
$za->close();
// Download If enabled
if ($download_file)
{
ob_get_clean();
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . basename($zip_file_name) . ";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($zip_file_name));
readfile($zip_file_name);
}
}
else
{
echo 'Could not create a zip archive';
}
?>
I am trying to read and get the size of the zip file in PHP.
Following is my code:
function create_zip($files, $file_name, $overwrite = false) {
foreach ($files as $imglink) {
$img = file_get_contents($imglink);
$destination_path = $_SERVER['DOCUMENT_ROOT'] . 'demoproject/downloads/' . time() . '.jpg';
file_put_contents($destination_path, $img);
$imgFiles[] = $destination_path;
}
if (file_exists($file_name) && !$overwrite) {
return false;
}
$valid_files = array();
if (is_array($imgFiles)) {
foreach ($imgFiles as $file) {
$valid_files[] = $file;
}
}
if (count($valid_files)) {
$zip = new ZipArchive();
if ($zip->open($file_name, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
echo "Sorry ZIP creation failed at this time";
}
foreach ($valid_files as $file) {
$zip->addFile($file, pathinfo($file, PATHINFO_BASENAME));
}
$count = $zip->numFiles;
$resultArr = array();
$resultArr['count'] = $count;
$resultArr['destination'] = $file_name;
$filename = $file_name;
$filepath = $_SERVER['DOCUMENT_ROOT'] . 'demoproject/';
$fileSize = filesize($filepath . $filename) / 1024;
echo 'size of the file is : ' . $fileSize . ' kb';
exit;
// $size = 0;
// $resource = zip_open($filepath . $filename);
// while ($dir_resource = zip_read($resource)) {
// $size += zip_entry_filesize($dir_resource);
// }
header("Pragma: no-cache");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . zip_entry_filesize($filepath . $filename));
if (#readfile($filepath . $filename) === false) {
header('http://localhost/demoproject/fbindex.php');
return 500;
} else {
header('Location:http://localhost/demoproject/fbindex.php');
return 200;
}
} else {
return false;
}
}
$files : contain the array of images and
$file_name : contain name of file : that is : $file_name = time() . ".zip";
In the above code $filename contains the actual zip file and $filepath contains the location of the zip file.
The issue is it's reading the file but always showing its size 0 instead of actual file size.
This is I am doing :
echo $size;
O/P : 0
Where am I going wrong? Need Help. Thanks
try this -
$fileSize = filesize($filepath . $filename)/1024;
echo 'size of the file is : '.$fileSize.' kb';
Shouldn't you close ZIP file just after adding files to it?
$zip->close();
Try clearstatcache() just before calling filesize().
Closing your zip file before all this is also a great idea.
I know I'm a bit late on this, but who knows?