Extract a file from a zip archive then rename it - php

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();
}

Related

php zip archive is adding the files with no size

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);

get_file_contents of zipped file

I've got a ZIP file sitting on my server. I want to unzip it and then save the completely file contents into just one variable.
I do NOT want to save the unzipped file on my server or on a visitor's computer. I just need all of the contents of that zipped file stored in a variable that I can play around with and eventually show on the screen. Every other solution I've found for this problem includes resaving the file in unzipped form.
How can I do this with get_file_contents, or any other function?
You can simply find out the file names within the ZIP Archive with PHPs ZipArchive for example. try this (have not tested it but you should be able to get it to work) :
$za = new ZipArchive();
$za->open('archive.zip');
$fileContents = array();
for( $i = 0; $i < $za->numFiles; $i++ ) {
$stat = $za->statIndex( $i );
$fp = $z->getStream($stat['name']);
if(!$fp) exit("failed\n");
$contents = '';
while (!feof($fp)) {
$contents .= fread($fp, 1000);
}
fclose($fp);
$fileContents[$stat['name']] = $contents;
}
Once you know the names of the files within the Zip you can also use something like this:
$path = sprintf('zip://%s#%s', $zipArchive, $fileNameInZipArchive);
$fileData = file_get_contents($path);

Extract folder name only from zip archive

I have created a PHP script that uploads file and extract it and get folder name inside the zip and insert its name and path into db. However it doesn't extract the folder name from zip archive and doesn't gets path name like I want. It extracts all direcotories and file names I just want directory names. Lets say I have zip file called abc.zip and it contains folders like this
a ->b->c
ab ->bc
What I want is to be able to get only parnet directory names like a and b currently it gets all directory names and file names.
$zip = new ZipArchive;
$zip->open($filen);
$zip->extractTo($path);
$zip->close();
$zip = new ZipArchive;
if ($zip->open($filen) === true) {
for($i = 0; $i < $zip->numFiles; $i++) {
$filename = $zip->getNameIndex($i);
$fileinfo = pathinfo($filename);
$db->con->query("Insert into files (rand) values ('$filename')");
}
$zip->close();
}
You could do:
$fileinfo = pathinfo($filename,PATHINFO_DIRNAME);
$db->con->query("Insert into files (rand) values ('$fileinfo')");

file_put_contents in to new directory

I have the following code, which as you can see i use to create a new directory then unzip a file.
<?php
function unzip_to_s3() {
// Set temp path
$temp_path = 'wp-content/uploads/gravity_forms/1-9e5dc27086c8b2fd2e48678e1f54f98c/2013/02/tmp/';
// Get filename from Zip file
$zip_file = 'archive.zip';
// Create full Zip file path
$zip_file_path = $temp_path.$zip_file;
// Generate unique name for temp sub_folder for unzipped files
$temp_unzip_folder = uniqid('temp_TMS_', true);
// Create full temp sub_folder path
$temp_unzip_path = $temp_path.$temp_unzip_folder;
// Make the new temp sub_folder for unzipped files
if (!mkdir($temp_unzip_path, '0755', true)) {
die('Error: Could not create path: '.$temp_unzip_path);
}
// Unzip files to temp unzip folder, ignoring anything that is not a .mp3 extension
$zip = new ZipArchive();
$filename = $zip_file_path;
if ($zip->open($filename)!==TRUE) {
exit("cannot open <$filename>\n");
}
for ($i=0; $i<$zip->numFiles;$i++) {
$info = $zip->statIndex($i);
$file = pathinfo($info['name']);
if(strtolower($file['extension']) == "mp3") {
file_put_contents(basename($info['name']), $zip->getFromIndex($i));
} else {
$zip->deleteIndex($i);
}
}
$zip->close();
}
unzip_to_s3();
?>
The unzip code was courtesy of #TotalWipeOut from one of my other posts. It currently unzips just mp3 files to my base directory, but i want to put them in my newly created folder.
I'm very new to PHP so have been trying my best with this, but i can't figure out how to change the file_put_contents(basename($info['name']), $zip->getFromIndex($i)); line to get it to put the files in my new folder?
As Marc B. mentioned you need to include the path to the directory you are putting the file in.
using your code:
file_put_contents($temp_unzip_path."/".basename($info['name']), $zip->getFromIndex($i));
I would also suggest reading a little more about the basics of PHP.

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