Php create zips without file path inside zip

I am trying to use php to create a zip file (which it makes - taken from this page - http://davidwalsh.name/create-zip-php ), however inside the zip file are all the folder names in the file itself.

Is it possible to have only a file inside zip minus all folders?

Here is my code:

function create_zip($files = array(), $destination = '', $overwrite = true) { if(file_exists($destination) && !$overwrite) { return false; }; $valid_files = array(); if(is_array($files)) { foreach($files as $file) { if(file_exists($file)) { $valid_files[] = $file; }; }; }; if(count($valid_files)) { $zip = new ZipArchive(); if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { return false; }; foreach($valid_files as $file) { $zip->addFile($file,$file); }; $zip->close(); return file_exists($destination); } else { return false; }; }; $files_to_zip = array('/media/138/file_01.jpg','/media/138/file_01.jpg','/media/138/file_01.jpg'); $result = create_zip($files_to_zip,'/...full_site_path.../downloads/138/138_files.zip'); 
+41
php zip folders
Oct 22 2018-10-10T00:
source share
3 answers

The problem is that $zip->addFile passed the same two parameters.

According to the documentation :

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

file name
The path to the file to be added.

Localname
local name inside the zip archive.

This means that the first parameter is the path to the actual file in the file system, and the second is the path and file name that the file will have in the archive.

When delivering the second parameter, you want to remove the path from it when adding it to the zip archive. For example, on Unix-based systems, this would look like this:

 $new_filename = substr($file,strrpos($file,'/') + 1); $zip->addFile($file,$new_filename); 
+105
Oct 22 '10 at 1:05
source share
β€” -

I think the best option:

 $zip->addFile($file,basename($file)); 

Which simply extracts the file name from the path.

+32
Apr 28 '15 at 17:19
source share

This is just another method that I have found for me.

 $zipname = 'file.zip'; $zip = new ZipArchive(); $tmp_file = tempnam('.',''); $zip->open($tmp_file, ZipArchive::CREATE); $download_file = file_get_contents($file); $zip->addFromString(basename($file),$download_file); $zip->close(); header('Content-disposition: attachment; filename='.$zipname); header('Content-type: application/zip'); readfile($tmp_file); 
0
Feb 25 '17 at 21:36
source share



All Articles