PHP Create a Zip archive for file only particular extension - php

How to create Zip archive for file only particular extension in my case .TIF .JPG .TXT

currently i have added single extensions in code you can modify it later on.
<?php
/* creates a compressed zip file */
function create_zip($files = array(), $destination = '', $overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if (file_exists($destination) && !$overwrite) {
return false;
}
//vars
$valid_files = array();
//if files were passed in...
if (is_array($files)) {
//cycle through each file
foreach ($files as $file) {
//make sure the file exists
if (file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if (count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach ($valid_files as $file) {
$zip->addFile($file, $file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
} else {
return false;
}
}
//your directory path where all files are stored
$dir = 'D:\xampp\htdocs\samples\zip';
$files1 = scandir($dir, 1);
// $ext = "png"; //whatever extensions which you want to be in zip.
$ext = ['jpg','tif','TXT']; //whatever extensions which you want to be in zip.
$finalArray = array();
foreach ($files1 as $key => $value) {
$getExt = explode(".", $value);
if ( in_array($getExt[1] , $ext) ) {
$finalArray[$key] = $value;
}
}
$result = create_zip($finalArray, 'my-archive' . time() . '.zip');
if ($result) {
echo "Operation done.";
}
?>
i think this is what you want.
let me know if you have any issue.

Related

Issue with Arabic file names while compress with Codeigniter zip library

I have certain files to compress and some of them have Arabic names, Upon extraction, they come out corrupted.
My PHP version is 7.2.18 and I am using the Codeigniter 3.1 framework.
Actual file name : كلمة العينة.docx
Compressed filename : +â+ä+à+¬_+º+ä+¦+è+å+¬.docx
public function generate_zip() {
$this->load->library('zip');
$zip_files = $this->document_model->get_documents();
foreach ($zip_files as $zip_file) {
$this->zip->read_file('uploads/documents/' . $zip_file->document_file_name);
}
$this->zip->download('temp.zip');
}
Hi Please try with the below code.
/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
$files_to_zip = array(
'عينة.txt',
);
//if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'my-archive.zip');

ZipArchive sending corrupt files

I am using the ZipArchive class to create a ZIP file and stream it to the client but all archives are not generated correctly.
Any suggestions?
<?php
if(file_exists('../../../thure/uploads/nestingen/58861.pdf'))
{
$files = array('../../../thure/uploads/nestingen/58861.pdf');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
exit;
}
else
{
echo 'file not found';
}
?>
Function (writed by David)
/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
Sample Usage
$files_to_zip = array(
'file1',
'file2',
'file3'
);
//if true, good; if false, zip creation failed
$result = create_zip($files_to_zip,'my-archive.zip');

ZipArchive - zip is not getting created, but throws no errors

I'm struggling with creating zips with ZipArchive. I've modified a function that let's me create a zip from an array of file paths.
Can you spot any faults in this code, anything that prevents the zip file from being created?
// Function to create a zip archive for the low res images
function create_zip_lres($files = array(), $destination = '', $overwrite = false) {
// If the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
$valid_files = array();
// If files were passed in
if(is_array($files)) {
foreach($files as $file) {
// Make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
// If we have good files
if(count($valid_files)) {
// Create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
// Add the files
foreach($valid_files as $file) {
$basename = basename($file);
$zip->addFile($file, $basename);
}
// DEBUG
echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
if ($zip->close()) {
echo ' - Success!';
echo '<br>';
echo 'Your zip path is: ' . $destination;
} else {
echo ' - Failed!';
}
// DEBUG
echo '<br>';
print_r($zip);
// Return filepath for zip
return $destination;
}
else {
return false;
}
}
// getting the images array
$resize_images = resize_images();
// destination path
$lres_directory = get_lres_full_upload_dir() . get_the_title() . '-low-res.zip';
if (function_exists('create_zip_lres')) {
create_zip_lres($resize_images, $lres_directory);
} else {
}
I've added some debugging lines to find out what's happening and although it's telling me everything looks fine, no file is created.
The zip archive contains 3 files with a status of 0 - Success!
Your zip path is: http://media.mysite.com/wp-content/uploads/lres-download-manager-files/Knus 1400-low-res.zip
ZipArchive Object ( [status] => 0 [statusSys] => 0 [numFiles] => 0 [filename] => [comment] => )
I have another solutions for dynamic array values enter to zip files.I have tested this is working fine.
Hope this helps:
<?php
//Our Dynamic array
$array = array( "name" => "raaaaaa",
"test" => "/sites/chessboard.jpg"
);
//After zip files are stored in this folder
$file= "/sites/master.zip";
$zip = new ZipArchive;
echo "zip started.\n";
if ($zip->open($file, ZipArchive::CREATE) === TRUE) {
foreach($array as $path){
$zip->addFile($path, basename($path));
echo "$path was added.\n";
}
$zip->close();
echo 'done';
} else {
echo 'failed';
}
?>
zipping multiple files to one zip file.
For Multiple files you can use this code for zip the specific folders.
I have tried this code and successfully zipped multiple files into one zip file.
I think this is help to your requirement.
<?php
function Zip($source, $destination)
{
echo "called function";
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
// Ignore "." and ".." folders
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
continue;
$file = realpath($file);
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
Zip('D:/tmp','D:/tmp/compressed.zip',true);
?>
Hope this helps

Best way to properly name files within zip archive

I have a function that creates zip files when passed an array of files which works beautifully.
$zip_file = create_zip($_FILES['myfile']['tmp_name'],$target);
But what happens is that the files in the zip archive all have the tmp names and no extensions. What would be the best way to alter the array I pass to the function such that the files are named the same way as when they are uploaded?
I've rewritten create_zip to include a localnames parameter. Pass in the $_FILES['myfile']['name'] for the files' original names.
function create_zip($files = array(),$localnames=array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files to archive
for ($i = 0; $i < count($valid_files); $i++) {
$zip->addFile($valid_files[$i],$localnames[$i]);
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
return file_exists($destination);
}
else
{
return false;
}
}
Usage:
$zip_file = create_zip($_FILES['myfile']['tmp_name'], $_FILES['myfile']['name'],
$target);

zip generating function generating blank files

I am using this function to generate zip files:
function create_zip($files = array(),$destination = '',$overwrite = false) {
//if the zip file already exists and overwrite is false, return false
if(file_exists($destination) && !$overwrite) { return false; }
//vars
$valid_files = array();
//if files were passed in...
if(is_array($files)) {
//cycle through each file
foreach($files as $file) {
//make sure the file exists
if(file_exists($file)) {
$valid_files[] = $file;
}
}
}
//if we have good files...
if(count($valid_files)) {
//create the archive
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
return false;
}
//add the files
foreach($valid_files as $file) {
$zip->addFile($file,$file);
//echo $file;
}
//debug
//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
//close the zip -- done!
$zip->close();
//check to make sure the file exists
echo $destination;
return file_exists($destination);
}
else
{
return false;
}
}
I am using this to zip a vanilla, unaltered Wordpress install.(http://wordpress.org/) However for some reason the wp-content folder is having a 'ghost' empty file generated with it's name. The folder (and everything else) itself compresses correctly, but most unzip applications (including php's own extractTo()) break when they reach this unwanted file due to the name conflict.
I've looked into the folder/file structure and as far as I can see the only difference of note between this and the other folders in the site is that it is the biggest at 5.86 mb.
Can anyone suggest a fix / workaround?
This is the sample example to zip a folder.
<?php
function Create_zipArch($archive_name, $archive_folder)
{
$zip = new ZipArchive;
if ($zip->open($archive_name, ZipArchive::CREATE) === TRUE)
{
$dir = preg_replace('/[\/]{2,}/', '/', $archive_folder . "/");
$dirs = array($dir);
while (count($dirs))
{
$dir = current($dirs);
$zip->addEmptyDir($dir);
$dh = opendir($dir);
while ($file = readdir($dh))
{
if ($file != '.' && $file != '..')
{
if (is_file($file))
$zip->addFile($dir . $file, $dir . $file);
elseif (is_dir($file))
$dirs[] = $dir . $file . "/";
}
}
closedir($dh);
array_shift($dirs);
}
$zip->close();
$result='success';
}
else
{
$result='failed';
}
return $result;
}
$zipArchName = "ZipFileName.zip"; // zip file name
$FolderToZip = "zipthisfolder"; // folder to zip
echo Create_zipArch($zipArchName, $FolderToZip);
?>

Categories