Creation of .zip with php

4

I'm trying to create a folder compressed with php at the moment it adds a single file but the idea is to be dynamic.

function crear_zip($id_paciente){
    $files = array( 'C:\xampp\htdocs\bitnami.txt' );
    $zipname = 'C:\xampp\htdocs\zipped_file.zip';
    $zip = new ZipArchive;
    $zip->open($zipname, ZipArchive::CREATE); 
    foreach ($files as $file) {
      $zip->addFile($file);
    }
    $zip->close();
}

The problem is that in the .zip it is a copy of the path I gave it and not the file try giving it only the name of the file but apparently it does not find it and does not create the .zip .. idea? .. Thanks in advance

    
asked by Laura Leon 27.12.2016 в 16:42
source

1 answer

6

The problem is that you do not pass the second parameter to the function $zip->addFile , and therefore assume the same file name (including the route).

According to the documentation : (my free translation)

  

ZipArchive bool :: addFile (string $ filename [ string $ localname ])

     

filename
  The path to the file that is added.

     

localname
  The local name within the ZIP file.

This means that the first parameter is the path to the actual file that you want to add to the server's file system, while the second is the path and file name that it will have inside the file ZIP compressed.

You must then pass the second parameter, and in this use only the name of the file (for which you can use the function basename . Something similar to:

function crear_zip($id_paciente){
    $files = array( 'C:\xampp\htdocs\bitnami.txt' );
    $zipname = 'C:\xampp\htdocs\zipped_file.zip';
    $zip = new ZipArchive;
    $zip->open($zipname, ZipArchive::CREATE); 
    foreach ($files as $file) {
      $localfile = basename($file);
      $zip->addFile($file, $localfile);
    }
    $zip->close();
}
    
answered by 27.12.2016 / 17:00
source