Download selected files into zip format in wordpress - php

I am using a wordpress template page download.php and the code is :
$ck=$_REQUEST['select'];
$num=count($ck);
$zip_file_name='demodown.zip';
$zip = new ZipArchive();
if ($zip->open($zip_file_name, ZIPARCHIVE::CREATE )!==TRUE)
{
exit("cannot open <$zip_file_name>\n");
}
$file_path = $_SERVER['DOCUMENT_ROOT']."/lab4/brazil_resource/wp-content/pdf_upload/";
for($i=0;$i<$num;$i++)
{
$sql=mysql_query("select * from wp_pagecontent where id='$ck[$i]'");
$f=mysql_fetch_array($sql);
$files=$f['pdf_file'];
$zip->addFile($file_path.$files,$files);
}
$zip->close();
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_file_name.'"');
exit;
Using the above code I cannot zip the files that are selected. The download files in showing 0 bytes size.
Please help

I had solved it now finally
$zip_file_name='demo.zip';
$zip = new ZipArchive();
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);
$file_path = content_url()."/pdf_upload/";
foreach($_REQUEST['select'] as $file)
{
$download_file = $file_path.$file;
$download_file2 = file_get_contents($download_file);
$zip->addFromString('files/'.$file,$download_file2);
}
$zip->close();
if(file_exists($tmp_file))
{
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_file_name.'"');
readfile($tmp_file);
// remove zip file is exists in temp path
}

I have solved the other issue with the following code:
$zip_file_name='demo.zip';
$zip = new ZipArchive();
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);
for($i=0;$i<$num;$i++)
{
$sql=mysql_query("select * from wp_pagecontent where id='$ck[$i]'");
$f=mysql_fetch_array($sql);
$files=$f['pdf_file'];
$download_file = file_get_contents($files);
//$fe=$file_path.$files;
//$zip->addFromString(basename($fe),file_get_contents($fe));
$zip->addFromString(basename($files),$download_file);
}
$zip->close();
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_file_name.'"');
header("Content-length: ".filesize($zip_file_name));
readfile($tmp_file);
exit;

Related

Download multiple zip file

I want download multiple zip for multiple image at a time.But my code crate only one zip file for all image.
foreach ($data as $key => $files) {
/*$fileName="file.zip";*/
$fileName = $key.'.zip';
$tmpFile = tempnam('/tmp', '');
$zip = new ZipArchive;
$zip->open($tmpFile, ZipArchive::CREATE);
foreach ($files as $file) {
// download file
$fileContent = file_get_contents($file);
$zip->addFromString(basename($file), $fileContent);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$fileName);
header('Content-Length: ' . filesize($tmpFile));
readfile($tmpFile);
echo $fileName;
unlink($tmpFile);
}

Zip download issue in php

if(isset($_REQUEST['create_all']))
{
$app_id = $_REQUEST['app'];
$fullpath = array();
$dir = dirname(__FILE__);
foreach($language_array as $key_lang=>$name_lang)
{
$path = $dir."/uploaded_xml/".$app_id."/";
if(!is_dir($path))
{
mkdir($path,0777);
chmod($path,0755);
}
$QUERY=mysql_query("select a.process_flag,a.field_id,a.field_name,a.xml_status,b.*,c.process_flag,b.lang_id from app_lang_fieldmaster_new a left join app_lang_translatetxt_new b on a.field_id=b.field_id left join app_lang_user_status c on a.field_id=c.field_id left join app_wise_lang_fields d on a.field_id=d.field_id where a.process_flag='0' and c.process_flag='6' and b.lang_id='".$key_lang."' and a.xml_status='1' and a.module_master_id='1' and d.app_id='".$app_id."' group by 2",$cont);
//create the xml document
$xmlDoc = new DOMDocument("1.0", "UTF-8");
//create the root element
$root = $xmlDoc->appendChild(
$xmlDoc->createElement("resources"));
while($row=mysql_fetch_object($QUERY))
{
if($key_lang==9)
{
$xml_string = $xmlDoc->createElement( "string",trim($row->translate," "));
$xml_string->setAttribute( "name",$row->field_name);
$root->appendChild($xml_string);
}
else
{
$xml_string = $xmlDoc->createElement( "string",trim(base64_decode($row->translate)," "));
$xml_string->setAttribute( "name",$row->field_name );
$root->appendChild($xml_string);
}
}
header("content-type: text/plain; charset=ISO-8859-15");
//make the output pretty
$xmlDoc->formatOutput = true;
$string = $xmlDoc->saveXML();
$handle = fopen($path.$name_lang.".xml","w");
fwrite($handle,$string);
fclose($handle);
// $string = $xmlDoc->save($path.$name_lang.".xml");
$fullpath[$key_lang] = $path.$name_lang.".xml";
}
ob_clean();
flush();
//zip file creation
$zip = new ZipArchive();
//zip file name
$FilePath = $app_id.".zip";
$full_path_zip = 'https://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/".$FilePath;
//check if file exists if yes then delete
if(file_exists(dirname(__FILE__)."/uploaded_xml/".$FilePath))
{
unlink (dirname(__FILE__)."/uploaded_xml/".$FilePath);
}
//open zip file to add files to zip file
if ($zip->open(dirname(__FILE__)."/uploaded_xml/".$FilePath, ZIPARCHIVE::CREATE) != TRUE)
{
die ("Could not open archive");
}
//$zip->addFile("file_path","file_name");
// loop through each file
foreach($language_array as $key=>$name)
{
//add files to zip
$zip->addFile($fullpath[$key],$name.".xml");
}
// close and save archive
$zip->close();
// header_remove();
echo $full_path_zip;
ob_clean();
flush();
$filename = dirname(__FILE__)."/uploaded_xml/".$FilePath;
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$filename.'"');
// echo dirname(__FILE__)."/uploaded_xml/".$FilePath;
str_replace(".php",".zip",$filename);
$file_content = file_get_contents($filename); // To download the ZIP file
print($file_content);
}
i am creating a zip file which contains some xml files from server, i am adding that xml files to zip and then trying to download the zip but it is downloading .php file. here is my code
$xmlDoc = new DOMDocument("1.0", "UTF-8");
//create the root element
$root = $xmlDoc->appendChild(
$xmlDoc->createElement("resources"));
while($row=mysql_fetch_object($QUERY))
{
if($key_lang==9)
{
$xml_string = $xmlDoc->createElement( "string",trim($row->translate," "));
$xml_string->setAttribute( "name",$row->field_name);
$root->appendChild($xml_string);
}
else
{
$xml_string = $xmlDoc->createElement( "string",trim(base64_decode($row->translate)," "));
$xml_string->setAttribute( "name",$row->field_name );
$root->appendChild($xml_string);
}
}
header("content-type: text/plain; charset=ISO-8859-15");
//make the output pretty
$xmlDoc->formatOutput = true;
$string = $xmlDoc->saveXML();
$handle = fopen($path.$name_lang.".xml","w");
fwrite($handle,$string);
fclose($handle);
// $string = $xmlDoc->save($path.$name_lang.".xml");
$fullpath[$key_lang] = $path.$name_lang.".xml";
}
ob_clean();
flush();
//zip file creation
$zip = new ZipArchive();
//zip file name
$FilePath = $app_id.".zip";
$full_path_zip = 'https://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/".$FilePath;
//check if file exists if yes then delete
if(file_exists(dirname(__FILE__)."/uploaded_xml/".$FilePath))
{
unlink (dirname(__FILE__)."/uploaded_xml/".$FilePath);
}
//open zip file to add files to zip file
if ($zip->open(dirname(__FILE__)."/uploaded_xml/".$FilePath, ZIPARCHIVE::CREATE) != TRUE)
{
die ("Could not open archive");
}
//$zip->addFile("file_path","file_name");
// loop through each file
foreach($language_array as $key=>$name)
{
//add files to zip
$zip->addFile($fullpath[$key],$name.".xml");
}
// close and save archive
$zip->close();`
here is my download zip file
$file_content = file_get_contents(dirname(__FILE__)."/uploaded_xml/".$FilePath); // To download the ZIP file
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename="'.dirname(__FILE__)."/uploaded_xml/".$FilePath.'"');
echo $file_content;
it is downloading .php file with following content
PK ”R—I+ Qý
Bulgarian.xml­”ÁnÓ#†ï}Š•ïP¸õ¤B J•Z‰pµ{’X²×ÑzàR ¢¤ŠBHo`ª˜†¤q_aöø×NÔÕ*nkÏÎ73ÿÌlk÷U‰—¤Ò0‘mçáýŽ é'A(ûmçù³½{;Îng«¥(M2åSÚÙ¢•j»^Lm§§B’AêFÝÈ]žå’§fÌ…à+3Âñ£ýà9O[Ûµ{3i˜E‘«WQq–â'32'|Å.jî‚sž ÌÜ raÞØß%‡©äóM¡ü§«Œ»*ñßK5"|æÀNÌ1|s§Ù¨(³Ø푧3EnªÉ‹ôà0  ou­f,PzÁ?xʗͬHö‡iêÊDº²ïõÉ•®ï©JÅ3ÔqÁPr[ÏRÂOÏ8‡ cü<ÆyC©ûÒû/€’ÇÑA¥ä©yî-ù°êà°àíªµô*TèGYp¸¸ËŒó†…íË?H2ýt iÅGƒÖ#üú]~ÇßQ•Ã4XOúÝ+±GOŒl£,vnsÌÊä/øHû6<f‚/ïš6°÷šâÜsä8Z-¦ÔŸ<ß°WX€Úÿ‹²ù"IMêúö)V±lÚu¬Ùf÷=ϧ'¤É׉:ðºT=µ/ϬÄf$°9¹°/Žy_YÊk\k{íAûPK ”R—I„üa[€ Î Catalan.xml“ËN+1†÷<E”=—³c1„¸HH ±èa¹‰gj)—ÊI*x(6‡Gè‹áiT!¦=›(·ï÷Ûi®^ƒWkäL)ÎôŸ³­0Úä(ö3ýw~z©¯Ú“†1§Ês{¢T“˹Šp¦;&Œ.¿ðfœëöÎg°flnÎwÄ4¼ªÞ›’c'¡–ƒ˜nçÄÀ
Öà½Z!«Ý¡žÖ³K(['Nà,ä¢Û[êj¦ÍÇ4µbTƒéJe4¹ ...
If i change the extension of downloaded file from .php to .zip it is working fine.
Kindly help thanks in advance...
Remove this line:
echo $file_content;
// To download the ZIP file
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment;
filename="'.dirname(__FILE__)."/uploaded_xml/".$FilePath.'"');
Try this
$file_content = file_get_contents(dirname(__FILE__)."/uploaded_xml/".$FilePath); // To download the ZIP file
header('Cache-Control: public');
header('Content-Description: File Transfer');
header('Content-type: application/force-download');
header('Content-Disposition: attachment; filename="'.dirname(__FILE__)."/uploaded_xml/".$FilePath.'"');

PHP zipfile won't open

For the life of me, I cannot figure out why this zip file fails to open, it errors saying it cannot open the file. The SELECT is a couple of BLOB files in phpmyadmin. Here is the code:
$uploadQuery = mysqli_query($con, "SELECT * FROM upload WHERE majorarea = 'Big Data'") or die (mysql_error());
$files = $uploadQuery;
$zipname = 'papers.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
readfile($zipname);

Zip folder first then allow user to download it

On my site I want to have a link that can zip a particular folder including its content then allow the user to download it. It will be use for downloading a bundled files.
try this code:
$files[] = base_url().'uploads/'.$names->file_name;
pass your files into this $files[] array.
$zip = new ZipArchive();
$tmp_file = tempnam('.','');
$zip->open($tmp_file, ZipArchive::CREATE);
foreach($files as $file)
{ //echo $file; exit;
$download_file = file_get_contents($file);
$zip->addFromString(basename($file),$download_file);
}
$zip->close();
header('Content-disposition: attachment; filename=project_files.zip');
header('Content-type: application/zip');
readfile($tmp_file);

Change storage folder when create zip

I use this code to create ZIP file from PHP
ZIP is correctly created, but I have a little trouble when download zip.
On browser, ZIP name appear like this
.._.._storage_temp_2013-09-03-1378245354.zip
I'm like to mantain only
2013-09-03-1378245354.zip
Here code I use:
$files = array($frente, $verso);
//$zipname = '../../storage/file.zip';
$zipname = "../../storage/temp/".date('Y-m-d')."-".time().".zip"; // Zip name
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$new_filename = substr($file,strrpos($file,'/') + 1);
$zip->addFile($file,$new_filename);
//$zip->addFromString(basename($file), file_get_contents($file));
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
ob_clean();
flush();
readfile($zipname)
I have solved in this way:
$new_zipname = substr($zipname,strrpos($zipname,'/') + 1);
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$new_zipname);

Categories