zip Folder without using getRealPath - php

I'm trying to make zip file from a folder inside my localhost server which is my computer with windows 7 OS to a host .The problem is with using getRealPath for making the zip file the zip file content would be like this "D:\xampp\htdocs\mobl\admin\downloads" but I don't want those folders inside my zip file.
How should I make zip file without those folders and just the target folder ?
this is the code I'm using to zip the folder
enter code here
$zip = new ZipArchive;
$zip->open('downloads/'.$zipname,ZipArchive::CREATE);
// Initialize empty "delete list"
$filesToDelete = array();
// Create recursive directory iterator
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($rootPath),
RecursiveIteratorIterator::LEAVES_ONLY);
foreach($files as $name => $file) {
// Get real path for current file
$filePath = $file->getRealPath();
// Add current file to archive
$zip->addFile($filePath);
}
// Zip archive will be created only after closing object
$zip->close();
Thanks

Related

How to copy the source code of my website recursively into a zip file and download using PHP

Since my file manager doesn't allow me to download multiple files, instead only allowing me to download them one by one (which is tedious, and, eventually will become inefficient), I want to know how to download all my website file contents into a single zip folder. I found a code that works from geeksForGeeks, however it only zips on that current directory level (not recursively). I want every file on my website put into a zip folder while preserving their place in their corresponding folders.
The code I found:
// Enter the name of directory
$pathdir = "./";
// Enter the name to creating zipped directory
$zipcreated = "BackupFiles.zip";
// Create new zip class
$zip = new ZipArchive;
if($zip -> open($zipcreated, ZipArchive::CREATE ) === TRUE) {
// Store the path into the variable
$dir = opendir($pathdir);
while($file = readdir($dir)) {
if(is_file($pathdir.$file)) {
$zip -> addFile($pathdir.$file, $file);
}
}
$zip ->close();
}
How do I add the folders as well? It only zips the files of the current directory and not all the subfolders.

zip with ZipArchive to PPTX errors

Got a bit of a weird problem.
I have a folder with PowerPoint data that I need to zip and then rename to pptx.
If I manually create a .zip and copy the files into it, then rename, it works like expected, but when I use ZipArchive to archive the data and then rename the created file, it doesn't work.
The programmatically created archive is also a few kB smaller than the manually created one.
Archive comparison tools tell me that I've got the exact same files in both zips, including hidden files.
But here is where it gets really weird: if I make another, empty archive, then copy-paste the files from the programmatically created archive with a simple select, drag and drop, that new archive will work when renamed to a .pptx and has the same size as the first manually created file.
$dir = 'pptx/test/compiled';
$zip_file = 'pptx/test/file.zip';
// Get real path for our folder
$rootPath = realpath($dir);
// Initialize archive object
$zip = new \ZipArchive();
$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);
// Create recursive directory iterator
/** #var SplFileInfo[] $files */
$files = new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($rootPath),
\RecursiveIteratorIterator::LEAVES_ONLY
);
foreach ($files as $name => $file)
{
// Skip directories (they would be added automatically)
if (!$file->isDir())
{
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
}
}
// Zip archive will be created only after closing object
$zip->close();
update
This only seems to be a problem on Windows, when tested on a Mac, it works without issues.
I ran into this problem again, and after asking help on a LibreOffice forum (the problem was specific for Impress), I've discovered that in windows the filepaths used when archiving had backslashes, that caused the issues.
I've added two lines in my archiving function to clean up the paths:
// Get real and relative path for current file
$filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($rootPath) + 1);
// Replace backward with forward slashes, for compatibility issues
$filePath = str_replace('\\', '/', $filePath);
$relativePath = str_replace('\\', '/', $relativePath);
// Add current file to archive
$zip->addFile($filePath, $relativePath);
Now my code runs without problems. (I use the LibreOffice headless as an exec() to convert to pdf, which wouldn't work previously)

Files Inside Zip Without Path

I create a zip file with php with this code:
<?php
$file1 = '/home/##ACCOUNT##/public_html/##SITE##/images/uploadfiles/backup/file1.csv';
$file2 = '/home/##ACCOUNT##/public_html/##SITE##/images/uploadfiles/backup/file2.csv';
// CREATE THE ZIP
$files = array($file1, $file2);
$zipname = '/home/##ACCOUNT##/public_html/##SITE##/images/uploadfiles/backup/backup.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
?>
In the created zip i get 2 files as i want it but it also contains the tree/path of those files so opening the zip you have to navigate inside those folder to get to the files is there a away to just have the 2 files in the zip file1.csv & file2.csv without the folders?
I found the anwser i wanted in another post
php creating zips without path to files inside the zip
As Workaround use $localname (second parameter) to define and control file/directory structure inside the zip eg.
<?php
$zip->addFile($file, $localname_relative_path);
?>
You can use ZipArchive::renameName method to change name of the file being added or use ZipArchive::addFromString. In the second case you need to remember that you first need to read that file into memory, so it should only be used in consideration with memory available.
Also you can use second parameter to ZipArchive::addFile as suggested in other answer.
foreach ($files as $file) {
$localName = basename($file);
$zip->addFile($file, $localname);
}

Creating zip file with php

I am creating a zip file of a particular folder, I am using joomla 1.5 version in which i have a component of form submission and I want to create a zip file with submitted documents. On my localhost, its creating the zip file, when I test to remote server, It replaces the extension with some kind of a number, suppose we are creating a file test.zip, but its creating like this test.zip.a12345 and test.zip.b12345..
The code which I have used to create zip file:
$files = array(
'files/file1.jpg',
'files/file2.jpg',
'files/file3.jpg'
);
$zip = new ZipArchive();
$zip_name = "zipfile.zip";
if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
$error .= "* Sorry ZIP creation failed at this time";
}
foreach($files as $file){
$zip->addFile($file);
}
$zip->close();
and the output on local server is zipfile.zip
output on live server is : zipfile.zip.a11236 and zipfile.zip.b11236
You probably need to use the ZipArchive::OVERWRITE flag when opening the file.
It chooses another name because the file already exists?
See: http://php.net/manual/en/zip.constants.php

Zipping up a folder without extra folders in the zipped file

So, I understand it's pretty easy to zip a folder and its contents given that php.net and stackoverflow are full of sample codes. I am trying to zip up a folder as well. This is my code:
$zip = new ZipArchive;
$zip->open('myzip.zip', ZipArchive::CREATE);
foreach (glob("/Volumes/Data/Users/username/Desktop/Archive/some/thisFolder/*") as $file) {
$zip->addFile($file);
}
$zip->close();
My script is running in a folder, say on Desktop, and I want to zip thisFolder and its contents. The above code WORKS. But, the problem is that when I unzip the myzip.zip created, I get a structure like
Volumes>Data>Users>username>Desktop>Archive>some>thisFolder
and then I find the contents inside the 8th folder (thisFolder) in this case. How can I change this code so that when I unzip myzip.zip,I would straightaway see the folder thisFolder with the contents inside it instead of having to navigate through folders 7 times before getting my content?
I tried to change the path and silly things like that. But, it doesn't work.
Thanks
If you want everything in the file to be a name relative to your starting folder, use chdir() to start from there:
chdir("/Volumes/Data/Users/username/Desktop/Archive/some/thisFolder");
foreach (glob("*") as $file) {
$zip->addFile($file);
}
Actually, I don't think this will work when $file is a subdirectory -- addFile doesn't recurse automatically. There's a comment in the documentation that shows how to write a recursive zip function:
http://www.php.net/manual/en/ziparchive.addemptydir.php
bool ZipArchive::addFile ( string $filename [, string $localname ] )
filename
The path to the file to add.
localname
local name inside ZIP archive.
You can use the pathinfo function to each $file in your loop, in order to retrieve the filename without the path, and then, use it as second parameter to the addFile method.
pathinfo doc here
Here is an example that could solve your problem:
// Create your zip archive
$zip = new ZipArchive;
// open it in creation mode
$zip->open('myzip.zip', ZipArchive::CREATE);
// Loop on all your file
$mask = "/Volumes/Data/Users/username/Desktop/Archive/some/thisFolder";
$allAvailableFiles = glob($mask . "/*")
foreach ($allAvailableFiles as $file)
{
// Retrieve pathinfo
$info = pathinfo($file);
// Generate the internal directory
$internalDir = str_replace($mask, "", $info['dirname']);
// Add the file with internal directory
$zip->addFile($file, $internalDir . "/" . $info['basename']);
}
$zip->close();

Categories