How to compress folder and download, how to proceed in a simple way?

Asked

Viewed 18 times

0

I’ve been doing a lot of searches both google, forums and FB groups, but nothing that was explained was enough to clear my doubt, I believe that because I’m new in the area and I’m still pretty "dry" for some more complex examples, but so...

I need to compress a folder that is created in a process of searching records by date, compress and download it, being more direct the process is as follows, I do a search by period, it creates a folder with the "period" plays the generated files within it, now I need to know how to proceed to compress this folder download.

The php Zip lib I already have installed on the local server.

My code is currently that way:

<?php 
$data1 = '2019-02-07';
$data2 = '2019-02-08';
$pdo = new PDO("mysql:host=localhost;dbname=73519225000122", "root", "");
$buscar = $pdo->prepare("SELECT chave,conteudo FROM xml WHERE modelo = '55' AND data_gravacao BETWEEN date('$data1') AND date('$data2')");
$buscar->execute();
$buscar->bindColumn(1, $chave);
$buscar->bindColumn(2, $conteudo);
$linha = $buscar->fetchAll(PDO::FETCH_ASSOC);

mkdir( $dirPath = __DIR__.'/arquivos/temp/'.$data1.'-'.$data2.'', 0777);
chmod($dirPath, 0777);

  $generated = $linha;
  foreach ($linha as $key => $value) {

        $content=$value['conteudo'];
        $fileName=$dirPath.'/'.$value['chave'].'.xml';
        $result=file_put_contents ($fileName , $content);
        if ($result===FALSE) {
          // manipula erro, lança exceção, etc...
        } else {
            $generated=$fileName; // remember this file
          }
  }

And yes, I will need to delete both the folder and the zip, so that it does not take up space on the server, in case the client wishes to have the ".zip file" again, it needs to perform the date search again how to proceed?

1 answer

1


$zip = new ZipArchive();
$zip->open('nomeDoFicheiro.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);


$ficheiros = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($dirPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($ficheiros as $nome => $ficheiro )
{

    if (!$ficheiro ->isDir())
    {

        $camihoDoFicheiro = $ficheiro ->getRealPath();
        $camihoRelativoDoFicheiro = substr($ficheiro , strlen($dirPath) + 1);

        $zip->addFile($camihoDoFicheiro , $camihoRelativoDoFicheiro);
    }
}

$zip->close();

Browser other questions tagged

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