php zip archive is adding the files with no size - php

I got this working but when i look into the zip folder all the files size is 0. I tryed not adding the files to the zip and that worked, but when i try to add them to a zip the size goes to 0. Why is this.
here is my php
if(isset($_FILES['file'])){
$file_folder = "uploads/";
$zip = new ZipArchive();
$zip_name = time().".zip";
$open = $zip->open("zip/".$zip_name, ZipArchive::CREATE);
if($open === true){
for($i = 0; $i < count($_FILES['file']['name']); $i++)
{
$filename = $_FILES['file']['name'][$i];
$tmpname = $_FILES['file']['tmp_name'][$i];
move_uploaded_file($tmpname, "uploads/".$filename);
$zip->addFile($file_folder, $filename);
}
$zip->close();
if(file_exists("zip/".$zip_name)){
// zip is in there, delete the temp files
echo "Works";
for($i = 0; $i < count($_FILES['file']['name']); $i++)
{
$filenameu = $_FILES['file']['name'][$i];
unlink("uploads/".$filenameu);
}
} else {
// zip not created, give error
echo "something went wrong, try again";
}
}
}

Your problem lies with this line: $zip->addFile($file_folder, $filename);
Currently that passes a path to the /uploads/ directory as the first argument.
According to Zip::addFile documentation you should be passing the path to the file to add (this includes the file and extension).
So change your code to include the file name (you already have it as a variable $filename which is handy).
$zip->addFile($file_folder.$filename, $filename);

Related

zip file created but not moving to folder in php

files are being uploaded and added to zip the only problem is to move the zip to desired location.the permission is OK i have moved single file. Now i want to create a zip containing multiple files and then moving that zip to folder.
$uploaddir = 'upload/page/';
if($_FILES['image_file_holder']['name'] != '')
{
$total = count($_FILES['image_file_holder']['name']);
echo $total;
$imagarr = explode(".", "myserver.zip");
$newimgfile = $imagarr[0]."_".mt_rand().'.'.$imagarr[1];
$zipname = $newimgfile;
$upload = $uploaddir . $newimgfile;
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['image_file_holder']['name'][$i];
if ($tmpFilePath != ""){
$zip->addFile($tmpFilePath);
}
}
$zip->close();
echo "moving";
if(move_uploaded_file($zipname,$upload))
{
echo "done";
}
}

Extract a file from a zip archive then rename it

I have this file that gets downloaded at:
DownloadFile($reportDownloadUrl, $DownloadPath);
But it's a zip file. Inside of it, a CSV file gets created with a random name i.e random_name.csv
How do I extract this folder abc.zip in php and rename this file with random name to new_name.csv
Problem is that I can't use
$zip->renameName('currentname.csv','newname.csv');
since I don't have currentname.
This code inspects the file in zipLocation then iterates over them to check if there are csv files. If it finds something it copies inside the directory with its original name, then copies another copy with a new name.
$zipLocation = "path/to/file.zip";
$zip = new ZipArchive;
if ($zip->open($zipLocation) === true) {
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
if (pathinfo($filename, PATHINFO_EXTENSION)=="csv"){
$fileinfo = pathinfo($filename);
copy("zip://".$zipLocation."#".$filename, "./newname.csv");
copy("zip://".$zipLocation."#".$filename, "./".$fileinfo['basename']);
}
}
$zip->close();
}

ZipArchive:: check file extension

The following code unzips my uploaded file and extracts everything in a directory called PDF. It then proceeds to iterate through the files and return files to download.
My problem is I need to check the file extension. I would only like to return the PDF file back to the user but some of the uploaded files have unnecessary images.
How can I check the contents of the file to ensure the unzipped file is a PDF & only the PDF is returned back to the user?
<?php
$zip = new ZipArchive;
$res = $zip->open('/download/xxxx.zip');
if ($res === TRUE) {
$zip->extractTo('/download/pdf/');
for($i = 0; $i < $zip->numFiles; $i++)
{
echo 'download';
}
$zip->close();
} else {
echo 'Something went wrong :( ';
}
?>
Thank you
Dexas solution worked for me. Here's the code if you need it
I've added in comments to show what I've changed.
<?php
$zip = new ZipArchive;
$res = $zip->open('/download/xxxxx.zip');
if ($res === TRUE) {
$zip->extractTo('/download/pdf/');
for($i = 0; $i < $zip->numFiles; $i++)
{
//Load files into variable which can be used with the following... ['dirname'], ['basename'], ['extension'], ['filename']
$path_parts = pathinfo('/download/pdf/' . $zip->getNameIndex($i));
//If the extension is equal to PDF echo the code out
if($path_parts['extension'] === 'pdf')
{
echo 'download';
}
}
$zip->close();
} else {
echo 'Something went wrong :( ';
}
?>
You can check it's MIME type using finfo
$finfo = new finfo(FILEINFO_MIME);
$type = $finfo->file('/path/to/file');
if($type === 'application/pdf')
{
//do your stuff
}
For the extension part you can use pathinfo
$ext = pathinfo('/path/to/file', PATHINFO_EXTENSION);
In the end you should check both and decide is it PDF or not.

php zipArchive unzip only certain extensions

I'm in need of unziping uploaded content. But for security purposes must verify the files are only image files so that somebody can't add a php into the zip and then run it later.
While doing the unzip I need to preseverve the file structure as well.
$zip->extractTo($save_path . $file_name, array('*.jpg','*.jpeg','*.png','*.gif') );
doesn't return null. Is there a parameter I can use for this or must I iterate with a loop through the zip file using regex to match extensions and create the folders and save the files with code??
Thanks
from php.net, handling .txt files
<?php
$value="test.zip";
$filename="zip_files/$value";
$zip = new ZipArchive;
if ($zip->open($filename) === true) {
echo "Generating TEXT file.";
for($i = 0; $i < $zip->numFiles; $i++) {
$entry = $zip->getNameIndex($i);
if(preg_match('#\.(txt)$#i', $entry))
{
////This copy function will move the entry to the root of "txt_files" without creating any sub-folders unlike "ZIP->EXTRACTO" function.
copy('zip://'.dirname(__FILE__).'/zip_files/'.$value.'#'.$entry, 'txt_files/'.$value.'.txt');
}
}
$zip->close();
}
else{
echo "ZIP archive failed";
}
?>
for anyone who would need this in the future here is my solution. Thanks Ciro for the post, I only had to extend yours a bit. To make sure all folders are created I loop first for the folders and then do the extarction.
$ZipFileName = dirname(__FILE__)."/test.zip";
$home_folder = dirname(__FILE__)."/unziped";
mkdir($home_folder);
$zip = new ZipArchive;
if ($zip->open($ZipFileName ) === true)
{
//make all the folders
for($i = 0; $i < $zip->numFiles; $i++)
{
$OnlyFileName = $zip->getNameIndex($i);
$FullFileName = $zip->statIndex($i);
if ($FullFileName['name'][strlen($FullFileName['name'])-1] =="/")
{
#mkdir($home_folder."/".$FullFileName['name'],0700,true);
}
}
//unzip into the folders
for($i = 0; $i < $zip->numFiles; $i++)
{
$OnlyFileName = $zip->getNameIndex($i);
$FullFileName = $zip->statIndex($i);
if (!($FullFileName['name'][strlen($FullFileName['name'])-1] =="/"))
{
if (preg_match('#\.(jpg|jpeg|gif|png)$#i', $OnlyFileName))
{
copy('zip://'. $ZipFileName .'#'. $OnlyFileName , $home_folder."/".$FullFileName['name'] );
}
}
}
$zip->close();
} else
{
echo "Error: Can't open zip file";
}

Code to zip uploaded files fails to delete temporary files

I guys, i'm writting code to upload file, zip them and delete tmp file.
But when i use unlink function, it do not remove all file, someone can explain to me why ?
Concerned php code :
$zip = new ZipArchive();
$target_path = 'img/products/';
$zip->open($target_path.$id_insert.'.zip', ZIPARCHIVE::CREATE);
$img_count = $_POST['count_file'];
for ($i = 1; $i <= $img_count; $i++){
$temp = 'img'.$i;
$file = $i.'-'.$id_insert.'-'.$_FILES[$temp]['name'];
$path = $target_path.basename($file);
if(move_uploaded_file($_FILES[$temp]['tmp_name'], $path)) {
$zip->addFile($path, basename($file));
$files_to_delete[] = $path;
}
}
$zip->close();
foreach($files_to_delete AS $file){
//unlink(dirname(__FILE__).'/'.$path);
}
foreach($files_to_delete AS $file){
//unlink(dirname(__FILE__).'/'.$path);
}
In this block you should replace $path with $file since that's what you're foreaching them as. You get the error because after you unlink $path the first time, the file at $path is unlinked, but every other iteration of it tries to delete the same file (which is the last one assigned to the $path variable).

Categories