PHP zip archive adds extra folder - php

I have a piece of code which generates a .zip archive containing all files and folders from a given folder. It looks like this:
function zipDirectory($source, $destination, $flag = '')
{
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($flag)
{
$flag = basename($source) . '/';
//$zip->addEmptyDir(basename($source) . '/');
}
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = str_replace('\\', '/', realpath($file));
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $flag.$file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $flag.$file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString($flag.basename($source), file_get_contents($source));
}
return $zip->close();
}
zipDirectory($downloadID.'/','temp_'.$downloadID.'.zip', false);
$zip_file = 'temp_'.$downloadID.'.zip';
$file_name = basename($zip_file);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . $file_name);
header("Content-Length: " . filesize($zip_file)+15);
However, the resulting .zip archive ends up containing the specified folder, as well as an extra folder called "C:" with folders inside it, making up the absolute path to the root of my site. There are no files in this chain of folders.
I don't really know what could be causing this... Any ideas? Would be much appreciated.

Related

Exclude Folder while zipping using PHP

Hi Guys i want to zip my project folder so this i can backup it , i used this script which i found in GitHub :
function Zip($source, $destination)
{
$Exclude = ['assets','vendor','cache'];
if (is_string($source)) $source_arr = array($source);
if (!extension_loaded('zip')) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
foreach ($source_arr as $source)
{
if (!file_exists($source)) continue;
$source = str_replace('\\', '/', realpath($source));
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
if (!in_array($file, $Exclude)) {
$file = str_replace('\\', '/', 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();
}
The function working perfectly the only problem is it zips all the subfolder in my project when i don't want it to zip the assets & vendor folders .
Thanks fellow Developers .
At the beginning of the function you can define those paths in an $exclude array. Then, in your foreach($source_arr as $source) loop, check if realpath($source) is found in that $exclude array. If it is, continue, skipping the folder.
This solution isn't very portable though. If you're wanting to backup, I suggest using Github & create a private repository. You can then easily setup a .gitignore file that will prevent those directories you mentioned from being committed.

Codeigniter Zip directory and download

I am having a very strange problem when zipping a directory and try to download using codeigniter.
Here is the code
$this->load->library('zip'); //Loading the zip library
$directory = $_SESSION['directory-download-path']; //Getting the directory from session
$name = basename($directory); //get the name of the folder
$name = str_replace(" ", "_", $name).".zip"; //create the zip name
unset($_SESSION['directory-download-path']); //removing it from session
$this->zip->read_dir($directory); //read the directory
$this->zip->download($name); //download the zip
It is very simple. The problem occurs with the download. I get the zip file but when i extract it i get a file with .zip.cpgz and continues to extract similar files. Thus i think it is corrupted. Can you please help me why is this occurring. I have permissions and everything on the directory because i am doing other operations.
EDIT:
I found after some more research to add the second parameter as follows:
$this->zip->read_dir($directory, false); //read the directory
But still not working.
Another solution was to add
ob_end_clean();
just before the line: $this->zip->download($name); //download the zip
but still no success!
Since I had no response i made a function outside of codeigniter that zips files and folder recursively which is below:
public function Zip($source, $destination)
{
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);
if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..', "Thumbs.db")) )
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();
}
After this in the codeigniter controller i made this:
$this->projects->Zip($source, $destination);
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$name");
header("Content-length: " . filesize($destination));
header("Pragma: no-cache");
header("Expires: 0");
readfile($destination);
unlink($destination);
Of course the $destination should be to a temp folder where you have permissions 777 or equivalent so that when the file is sent to the client it will be deleted.
Hope this helps!

zipping a folder not working in php

I have created a script to upload a photo and place different sizes versions into a folder. After that, I want to zip that folder. The script is doing all the work I want except zipping the files. No error is showing up.
Here's the code:
session_start();
$_SESSION['upload_time']=time();
$target_dir = 'downloads/'.$_FILES['userImage']["name"].'-'.$_SESSION['upload_time'].'/';
if(!is_dir($target_dir)){
mkdir($target_dir);
}
$file4 = file_get_contents('assets/sizes.txt', true);
$data4=json_decode($file4,true);
foreach($data4 as $data){
$data=explode('_',$data);
$data1= preg_replace("/[^0-9]/","",$data[0]);
$data2= preg_replace("/[^0-9]/","",$data[1]);
///uploading photo and creating its different sizes
store_uploaded_image('userImage',$data1,$data2,$data1.'x'.$data2 ,$target_dir);
}
$zip = new ZipArchive();
// open archive
if ($zip->open('my-archive.zip', ZIPARCHIVE::CREATE) !== TRUE) {
die ("Could not open archive");
}
// initialize an iterator
// pass it the directory to be processed
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($target_dir));
// iterate over the directory
// add each file found to the archive
foreach ($iterator as $key=>$value) {
$zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");
}
// close and save archive
$zip->close();
echo "Archive created successfully.";
Try this code,For Local systems you can use this code for zip the specific folders.
Code:-
<?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('/downloads','/my-archive.zip',true);
?>
Hope this helps.

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

Every time I create zip file from PHP, there is one empty folder "\data"

Every time I create zip file from PHP, there is one empty folder "\data".
But there is no such folder in server.
When i unzip the zip file and browse that empty folder, it shows path something like:
\data/www/subdomains/site/httpdocs/
it looks like the absolute path of the folder i am trying to zip.
Here are my codes:
<?php
$file = tempnam("tmp","zip");
zip_directory($_GET['catname'].'/'.$_GET['directtozip'].'/',$file);
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="'.$_GET['directtozip'].'.zip"');
readfile($file);
unlink($file);
function zip_directory($source,$tempfile){
if(!extension_loaded('zip') || !file_exists($source)) return false;
$zip = new ZipArchive();
if(!$zip->open($tempfile,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){
// Excluded folders or file from zip.
$chk_1 = strstr($file,$source .'/'.'.svn');
if($chk_1){continue;}
$file = str_replace('\\', '/', 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));
}
}
}
elseif(is_file($source) === true) $zip->addFromString(basename($source), file_get_contents($source));
return $zip->close();
}
zip_directory($source,$tempfile);
?>
Thanks in advance.
What's with the last line zip_directory($source,$tempfile); because $tempfile is not defined.
Your code works OK for me
<?php
$file = tempnam("tmp","zip");
zip_directory('__z/', $file);
header('Content-Type: application/zip');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename="_zzz.zip"');
readfile($file);
unlink($file);
function zip_directory($source, $tempfile){
if(!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if(!$zip->open($tempfile, 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){
$chk_1 = strstr($file,$source .'/'.'.svn');
if($chk_1){continue;}
$file = str_replace('\\', '/', 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));
}
}
} elseif( is_file($source) === true ) {
$zip->addFromString(basename($source), file_get_contents($source));
}
return $zip->close();
}
?>

Categories