user3371408
user3371408

Reputation: 39

Download selected files into zip format in wordpress

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

Upvotes: 0

Views: 2185

Answers (2)

user3371408
user3371408

Reputation: 39

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
} 

Upvotes: 2

user3371408
user3371408

Reputation: 39

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;

Upvotes: 0

Related Questions