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.
Related
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.
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
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.
$path = '/home/username/www/;
if($zip = new ZipArchive){
if($zip->open('backup_'. time() .'.zip', ZipArchive::CREATE)){
if(false !== ($dir = opendir($path))){
while (false !== ($file = readdir($dir))){
if ($file != '.' && $file != '..' && $file != 'aaa'){
$zip->addFile($path . $file);
echo 'Adding '. $file .' to path '. $path . $file .' <br>';
}
}
}
else
{
echo 'Can not read dir';
}
$zip->close();
}
else
{
echo 'Could not create backup file';
}
}
else
{
echo 'Could not launch the ZIP libary. Did you install it?';
}
Hello again Stackoverflow! I want to backup a folder with all its content including (empty) subfolders and every file in them, whilst excluding a single folder (and ofcourse . and ..). The folder that needs to be excluded is aaa.
So when I run this script (every folder does have chmod 0777) it runs without errors, but the ZIP file doesn't show up. Why? And how can I solve this?
Thanks in advance!
have you tried to access the zip folder via PHP rather than looking in FTP as to whether it exists or not - as it might not appear immediately to view in FTP
function addFolderToZip($dir, $zipArchive, $zipdir = ''){
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
//Add the directory
if(!empty($zipdir)) $zipArchive->addEmptyDir($zipdir);
// Loop through all the files
while (($file = readdir($dh)) !== false) {
//If it's a folder, run the function again!
if(!is_file($dir . $file)){
// Skip parent and root directories, and any other directories you want
if( ($file !== ".") && ($file !== "..") && ($file !== "aa")){
addFolderToZip($dir . $file . "/", $zipArchive, $zipdir . $file . "/");
}
}else{
// Add the files
$zipArchive->addFile($dir . $file, $zipdir . $file);
}
}
}
}
}
After a while of fooling around this is what I found working. Use it as seen below.
$zipArchive = new ZipArchive;
$name = 'backups\backup_'. time() .'.zip';
$zipArchive->open($name, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
addFolderToZip($path, $zipArchive);
Here's my answer, checks if the modification time is greater then something as well.
<?php
$zip = new ZipArchive;
$zip_name = md5("backup".time()).".zip";
$res = $zip->open($zip_name, ZipArchive::CREATE);
$realpath = str_replace('filelist.php','',__FILE__);
$path = realpath('.');
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
if (is_file($object)) {
$file_count ++;
$epoch = $object->getMTime();
if($epoch>='1374809360'){ // Whatever date you want to start at
$array[] = str_replace($realpath,'',$object->getPathname());
}
}
}
foreach($array as $files) {
$zip->addFile($files);
}
$zip->close();
echo $zip_name.'-'.$file_count.'-'.$count_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);
?>