Download file as zip with PHP

Asked

Viewed 937 times

4

I have the following file coming from the database:

$sqlAnexos = mysqli_query($this->conexao,"SELECT * FROM arquivos");

while($jmArquivos = mysqli_fetch_object($sqlAnexos)){

...
echo "<a href='download.php?key=".$jmArquivos->IdCodArquivos."'>".$jmArquivos->Arquivos."</a>";
...
}

I would like to click on the link of the files, be downloaded as zip. I tried with the code below, but it did not work:

Page downloads.php

<?php
 $sqlArquivos = mysqli_query($this->conexao,"SELECT * FROM arquivos WHERE IdCodArquivos = '".$_REQUEST["key"]."';");
 $jmArquivos = mysqli_fetch_object($sqlArquivos);


    $zipar = new ZipArchive();
    $arquivo = $jmArquivos->Arquivos;
    if($zipar->open('nome_arquivo_zip.zip', ZIPARCHIVE::CREATE) == TRUE){
       $zipar->addFile($arquivo,$arquivo);
    }else{
      echo "Erro";
    }
    header("Content-Type: application/zip");
    header("Content-Length: ".filesize($arquivo));
    header("Content-Disposition: attachment; filename=".basename($arquivo).".zip");
    readfile($arquivo.".zip");
    $zipar->close();
    ?>
  • Ué, you generate a zip but serve the original archive... And I think you should close the zip before serving.

  • Hello bfavaretto. It gets to generate the zip but gives error while unzipping.

1 answer

1

I had similar problems for large ZIP files And I solved it this way:

In your php.ini, do it:

  • Upload_max_filesize - 1500 M
  • Max_input_time - 1000
  • Memory_limit - 640M
  • Max_execution_time - 1800
  • Post_max_size - 2000 M

In your donwload php file, do:

$filename = "MyFile.zip";     //nome do seu arquivo      
$filepath='../downloads/'.$filename;    //a pasta onde está o arquivo   
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");    
header("Content-Length: ".filesize($filepath)); 
header("Content-Disposition:attachment;filename=\"".basename($filepath)."\"");


while (ob_get_level()) 
{
 ob_end_clean();
 }
readfile($filepath);   
exit;
ob_start ();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.