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();}
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';
}
?>
Actually i want to change opencart download routh to new website, already download folder is:
/system/download
config.php
define('DIR_DOWNLOAD', '/system/download/');
and here is code from controller/account/download.php
if ($download_info) {
$file = DIR_DOWNLOAD . $download_info['filename'];
$mask = basename($download_info['mask']);
if (!headers_sent()) {
if (file_exists($file)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . ($mask ? $mask : basename($file)) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
if (ob_get_level()) {
ob_end_clean();
}
readfile($file, 'rb');
exit();
} else {
exit('Error: Could not find file ' . $file . '!');
}
} else {
exit('Error: Headers already sent out!');
}
} else {
$this->response->redirect($this->url->link('account/download', '', 'SSL'));
}
i want to buy a new server just for downloading, and now i want change opencart download route to new server. how can i do this?
Already download system is like this:
https://example.com/index.php?route=account/download/download&download_id=16
and it will get file from this directory:
/system/download/example.zip
but i want to get file from new server:
https://newserver.com/download/example.zip
Is it possible? I changed DIR_DOWNLOAD but no success. Any idea?
Yes you can, go with this easily:
$newserv = "http://newserver.com/";
$file = $newserv . $download_info['filename'];
$mask = basename($download_info['mask']);
<?PHP
function zipFilesAndDownload($file_names,$archive_file_name,$file_path){
$zip = new ZipArchive();
//create the file and throw the error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
//add each files of $file_name array to archive
foreach($file_names as $files) {
$zip->addFile($file_path.$files,$files);
}
$zip->close();
$zipped_size = filesize($archive_file_name);
header("Content-Description: File Transfer");
header("Content-type: application/zip");
header("Content-Type: application/force-download");// some browsers need this
header("Content-Disposition: attachment; filename=$archive_file_name");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-Length:". " $zipped_size");
ob_clean();
flush();
readfile("$archive_file_name");
unlink("$archive_file_name"); // Now delete the temp file (some servers need this option)
exit;
}
if(($_POST['formSubmit'])) {
//$file_names=$_POST['items'];// Always sanitize your submitted data!!!!!!
//$file_names = filter_var_array($_POST['items']);//works but it's the wrong method
$filter = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS) ;
$file_names = $filter['items'] ;
//Archive name
$archive_file_name= "zip.zip";
//Download Files path
$file_path= $leadon;
//cal the function
zipFilesAndDownload($file_names,$archive_file_name,$leadon);
}
?>
I have a working code here.
The main problem is
//Download Files path
$file_path= $leadon;
//cal the function
zipFilesAndDownload($file_names,$archive_file_name,$leadon);
This code
echo $leadon;
returns string images2/User/
And it doesn't create me the zip file ( well it creates a blank ) but if I manually type in the path
"images2/User/"
into
$file_path= and then I just change
zipFilesAndDownload($file_names,$archive_file_name,$file_path);
everything works fine can you tell me why is it so? And how can I change it:s
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)) );
Thanks to the users community on this forum, I wrote a very simple web form that allows my user to view text files from within their Internet browser.
I have now two functions whereby the text files returned by the search are compressed into a ZIP. Here's my code
function getFilesFromSite() {
$result = null;
$ZIPresult = null;
if (empty($_POST['DBSite'])) { return null; }
$mydir = MYDIR;
$dir = opendir($mydir);
$DBSite = $_POST['DBSite'];
$getfilename = mysql_query("select filename from search_table where site='" . $DBSite . "'") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
shell_exec("/bin/rm -f SearchResult.zip;/usr/bin/zip -9 SearchResult.zip ". $ZIPresult ." > /dev/null ");
//header for forced download
header("Pragma: public");
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
$fileName = 'SearchResult.zip';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Transfer-Encoding: binary");
header('Content-type: application/zip');
header("Content-length: " . filesize($fileName));
header('Content-Disposition: attachment; filename="' . $fileName . '"');
ob_start(); // Starts output buffering.
readfile($fileName); // "Outputs" the file.
$content = ob_get_flush(); // Grabs the output and assigns it to a variable.
print base64_encode($content);
}
function getFilesFromError() {
//Just a copy paste from above with different input parameter...
}
The problem is that the ZIP file with the contents from whatever search was done first gets downloaded over and over again. For instance, the results from getFilesFromSite() will always get downloaded even though I did a search with getFilesFromError() afterwards.
I suspect my headers are incorrectly set but I am not sure where.
PS: The new ZipArchive() library/class is not available on our production environment so I chose to use the Unix utility ZIP instead.
Using Base64 was actually not working for reasons well stated here. Instead, I turned zlib compression off and reverted back to using binary as output format. Finally, I set Content-Type to application/octet-stream in my header. Everything is working fine now ; here's my code:
function getFiles() {
ini_set('zlib.output_compression', 'Off');
$result = null;
$ZIPresult = null;
$cleanup = null;
$output = null;
$fileName = null;
//remove old zip if any
$cleanup = shell_exec("/bin/rm -f SearchResult.zip");
error_log("SHELL OUTPUT=>" . $cleanup, 0);
//test
if (empty($_POST['DBRIDs'])) { return null; }
$mydir = MYDIR; // set from the CONSTANT
$dir = opendir($mydir);
$DBRIDs = $_POST['DBRIDs'];
$getfilename = mysql_query("select /*! SQL_CACHE */ filename from automation where rid in (" . $DBRIDs . ")") or die(mysql_error());
while ($row = mysql_fetch_array($getfilename)) {
$filename = $row['filename'];
$result .= '<tr><td>' . $filename . '</td></tr>';
$ZIPresult .= basename($mydir) . '/' . $filename.' ';
}
if ($result) {
$result = "<table><tbody><tr><td>Search Results.</td></tr> $result</table>";
$output = shell_exec("/usr/bin/zip SearchResult.zip ". $ZIPresult ." ");
error_log("SHELL OUTPUT=>" . $output, 0);
$fileName = 'SearchResult.zip';
error_log("ZIP FILENAME=>" . $fileName, 0);
if (file_exists($fileName)) {
//header for forced download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($fileName));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fileName));
ob_clean();
flush();
readfile($fileName);
exit;
}
}
return $result;
}
Thanks to all for taking the time!!