Fetch everything in a folder based on extension and put into zip - php

I have to make 3 buttons. On button click I want to download all files from selected folder with correct extension in zip file. Eveything on wordpress site. The problem is, zip file is saving as .zip, but when I open it in notepad, there's HTML code. Thanks for help!
<?php
if(isset($_POST['3dsdownload'])) {dddownloads();}
function dddownloads(){
$dir = realpath("/autoinstalator/wordpress/wp-content/uploads/");
$scan_arr = scandir($dir);
$zip = new ZipArchive();
$zip->open('3ds.zip', ZipArchive::CREATE);
$files = array_diff($scan_arr, array('.','..') );
foreach ($files as $name => $file) {
if (!is_dir($file)){
$filePath = $dir.$file;
$file_ext = pathinfo($filePath, PATHINFO_EXTENSION);
if ($file_ext=="3ds" || $file_ext=="3DS") {
$zip->addFile($filePath, basename($filePath));
}
}
}
$zip->close();
header('Content-disposition: attachment; filename=3ds.zip');
header('Content-type: application/zip');
readfile('3ds.zip');
exit;
}
?>
<form method="post">
<input type="submit" name="3dsdownload"
value="3dsdownload"/>
</form>

The problem was buffer and path. After adding ob_clean() and fixing path, everything works fine! Final code:
<?php //Strona z pobieraniem wszystkich plikow z podziałem na formaty
//3ds
if(isset($_POST['3dsdownload'])) {dddownloads();}
function dddownloads(){
ob_clean();
$dir = (dirname(__DIR__,2)."/uploads/");
$scan_arr = scandir($dir);
$zip = new ZipArchive();
$zip->open('3ds.zip', ZipArchive::CREATE | ZIPARCHIVE::OVERWRITE);
$files = array_diff($scan_arr, array('.','..') );
foreach ($files as $name => $file) {
if (!is_dir($file)){
$filePath = $dir.$file;
$file_ext = pathinfo($filePath, PATHINFO_EXTENSION);
if ($file_ext=="3ds" || $file_ext=="3DS") {
$zip->addFile($filePath, basename($filePath));
}
}
}
$zip->close();
header('Content-disposition: attachment; filename=3ds.zip');
header('Content-type: application/zip');
header("Content-Transfer-Encoding: binary");
ob_end_clean();
readfile('3ds.zip');
exit;
}
?>

Related

Do not remove duplicate values from array

I have written this code to download files after adding them in a zip file. However, my code removes the files which have the same name ( duplicate ).
<?php
# define file array
$files = array(
'https://www.fbise.edu.pk/Old%20Question%20Paper/2017/SSC-II/Chemistry.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2018/SSC-II/Chemistry.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2018/SSC-II/Physics.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2017/SSC-II/Physics.PDF',
);
# create new zip object
$zip = new ZipArchive();
# create a temp file & open it
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);
# loop through each file
foreach ($files as $file) {
# download file
$download_file = file_get_contents($file);
#add it to the zip
$zip->addFromString(basename($file), $download_file);
}
# close zip
$zip->close();
# send the file to the browser as a download
header('Content-disposition: attachment; filename="my file.zip"');
header('Content-type: application/zip');
readfile($tmp_file);
unlink($tmp_file);
?>
So my question is,
How can I download duplicate files from an array?
or
How can I change the names of duplicate files?
Just rename your files.
<?php
# define file array
$files = array(
'https://www.fbise.edu.pk/Old%20Question%20Paper/2017/SSC-II/Chemistry.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2018/SSC-II/Chemistry.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2018/SSC-II/Physics.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2017/SSC-II/Physics.PDF',
);
# create new zip object
$zip = new ZipArchive();
# create a temp file & open it
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);
// Variable to Keep Filenames
$filename = '';
// Variable to add "-1, -2" to duplicate files
$i = 1;
# loop through each file
foreach ($files as $file) {
# download file
$download_file = file_get_contents($file);
if ( $filename == basename($file) )
{
// If this file already exists add "-1, -2"
$filename = $i . '-' . basename($file);
$i++;
} else
{
$filename = basename($file);
$i = 1;
}
#add it to the zip
$zip->addFromString($filename, $download_file);
}
# close zip
$zip->close();
# send the file to the browser as a download
header('Content-disposition: attachment; filename="my file.zip"');
header('Content-type: application/zip');
readfile($tmp_file);
unlink($tmp_file);
?>
Edit after #RiggsFolly Comment to support out of order duplicate files
<?php
# define file array
$files = array(
'https://www.fbise.edu.pk/Old%20Question%20Paper/2017/SSC-II/Chemistry.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2018/SSC-II/Chemistry.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2018/SSC-II/Physics.PDF',
'https://www.fbise.edu.pk/Old%20Question%20Paper/2017/SSC-II/Physics.PDF',
);
# create new zip object
$zip = new ZipArchive();
# create a temp file & open it
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);
// Array to keep filenames
$filenames = array();
# loop through each file
foreach ($files as $file) {
# download file
$download_file = file_get_contents($file);
if( array_key_exists( basename($file), $filenames ) )
{
$filename = $filenames[basename($file)] . '-' . basename($file);
$filenames[basename($file)] = $filenames[basename($file)] + 1;
} else
{
$filename = basename($file);
$filenames[basename($file)] = 1;
}
#add it to the zip
$zip->addFromString($filename, $download_file);
}
# close zip
$zip->close();
# send the file to the browser as a download
header('Content-disposition: attachment; filename="my file.zip"');
header('Content-type: application/zip');
readfile($tmp_file);
unlink($tmp_file);
?>

Set the name of Zip archive using ZipArchive class

The code I currently have, attached below, successfully writes files into an archive and initiates downloading of the file but the filename is a random alphanumeric string. A few examples of these file titles are:
IfTO57y8.zip
PFuuPgMD.zip
KUgWDc0T.zip
How can I set the name of the Zip folder to something more user-friendly?
function start_brochures_download( $brochures ) {
$confirmation = "Your download should begin shortly. \r\n";
$error = "Files not set \r\n";
$files = $brochures;
if( $files ) {
$zip = new ZipArchive();
$current_time = time();
$file_name = "Brochures-".$current_time;
$file_folder = wp_upload_dir();
$dir = $file_folder['path'];
$zip_file = $dir.'/'.$file_name.'.zip';
$zip->open( $zip_file, ZipArchive::CREATE );
foreach ($files as $file) {
if( !empty($file) ){
# download file
$download_file = file_get_contents($file);
#add it to the zip
$zip->addFromString(basename($file), $download_file);
}
}
$zip->close();
header('Content-disposition: attachment; filename="'.$zip_name.'"');
header('Content-type: application/zip');
header('Content-Length: ' . filesize($zip_file));
// header("Location: $zip_file");
readfile($zip_file);
} else {
echo $error;
}
}

Zip file is not downloading in Yii2

I am trying to download the zip file with many images.This code is working when i call the path in browser but not downloading when i call from Jquery ajax.Need to change or add anything in header?please help.
Controller:
public function actionZipdownload(){
$files = Yii::$app->request->post('imgsrc');
//it displays the URLs.
$zip = new \ZipArchive();
$tmp_file = tempnam('.', '');
$zip->open($tmp_file, ZipArchive::CREATE);
foreach ($files as $file) {
$download_file = file_get_contents($file);
$zip->addFromString(basename($file), $download_file);
}
$zip->close();
header('Content-disposition: attachment; filename="my file.zip"');
header('Content-type: application/zip');
readfile($tmp_file);
unlink($tmp_file);
}
Jquery:
$.ajax({
url:url+'site/zipdownload',
data:{'imgsrc':imgsrc},
type:'POST',
success:function(data){
//alert(data);
}
});
In console response:
I just ignore the Jquery Ajax and done it by Html::a with two actions..When i am calling the url in a tag then the file got downloaded.And also done some changes in controller.
Views:
<?=Html::a('Create Zip',['site/zipdownload'],['class'=>'btn btn-danger pull-left'])?>
<?=Html::a('Download',['site/download'],['class'=>'btn btn-danger pull-left'])?>
Controller:
public function actionZipdownload(){
$files = Yii::$app->request->post('img_src');
$zip = new \ZipArchive();
$tmp_file = 'uploads/images.zip';
if(file_exists($tmp_file)){
$zip->open($tmp_file, ZipArchive::OVERWRITE);
}
else{
$zip->open($tmp_file, ZipArchive::CREATE);
}
$i=1;
foreach ($files as $file) {
$download_file = file_get_contents($file);
$fileParts = pathinfo($file);
$filename = $i.explode("?",$fileParts['filename'])[0];
$zip->addFromString($filename, $download_file);
$i++;
}
$zip->close();
}
public function actionDownload(){
$path = 'uploads/images.zip';
if(file_exists($path)){
\Yii::$app->response->sendFile($path)->send();
unlink($path);
}
else{
return $this->redirect(['site/dashboard']);
}
}

Zip files in a folder and give the archive folder's name

I'm very new to php and I just made my first script, which is working fine, but is missing a final touch.
The script zips all files in the folder containing the php and creates a downloadable archive.
Here's the code
<?php
$zipname = 'test.zip';
$zip = new ZipArchive;
$zip->open('D://mypath//zip//$zipname', ZipArchive::CREATE);
if ($dir_handle = opendir('./')) {
while (false !== ($entry = readdir($dir_handle))) {
if ($entry != "." && $entry != ".." && !strstr($entry,'.php') && !strstr($entry,'.zip')) {
$zip->addFile($entry);
}
}
closedir($dir_handle);
}
else {
die('file not found');
}
$zip->close();
header('Content-Type: application/zip');
header("Content-Disposition: attachment; filename=$zipname");
header('Content-Length: ' . filesize($zipname));
header("Location: $zipname");
?>
What I'd like to achieve is having $zipname = "the name of the folder.zip"
So, if the php is inside "/mypath/blablabla/" i want my zip $zipname to be "blablabla.zip"
Any help will be appreciated!
EDIT:
here's the working code:
<?php
$zipname = getcwd();
$zipname = substr($zipname,strrpos($zipname,'\\')+1);
$zipname = $zipname.'.zip';
$zip = new ZipArchive;
$zip->open('D:/inetpub/webs/mydomaincom/zip/'.basename($zipname).'', ZipArchive::CREATE);
if ($dir_handle = opendir('./')) {
while (false !== ($entry = readdir($dir_handle))) {
if ($entry != "." && $entry != ".." && !strstr($entry,'.php')) {
$zip->addFile($entry);
}
}
closedir($dir_handle);
}
else {
die('file not found');
}
$zip->close();
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($zipname).'"');
header('Content-Length: ' . filesize($zipname));
header('Location: /zip/'.$zipname);
?>
You could use getcwd() :
http://php.net/manual/fr/function.getcwd.php
$zipname = getcwd();
It'll return the path of the current folder, then you could just hash the result to get only the name of the folder :
// We remove all the uneeded part of the path
$zipname = substr($zipname,strrpos($zipname,'\\')+1);
//Then we add .zip to the result :
$zipname = $zipname.'.zip';
This should do the trick.
And if you want to also use the name of the parent folder :
$zipname = getcwd();
// We remove the uneeded part of the path
$parentFolderPath = substr($zipname, 0,strrpos($zipname,'\\'));
$parentFolder = substr($parentFolderPath, strrpos($parentFolderPath,'\\')+1);
//Keep current folder name
$currentFolder = substr($zipname,strrpos($zipname,'\\')+1);
//Join both
$zipname = $parentFolder.'_'.$currentFolder;
//Then we add .zip to the result :
$zipname = $zipname.'.zip';
Instead of redirecting with header(), you could use readfile():
header('Content-Disposition: attachment; filename="'.basename($zipname).'"');
readfile($zipname);
With basename() only the last part is shown to the user and with readfile() you are giving out the actual file, no matter where it is.

how to create and download zip file without path directory [duplicate]

This question already has answers here:
php creating zips without path to files inside the zip
(4 answers)
Closed 9 years ago.
My code creates a ZIP file and downloads it in this ZIP folder some images exist.
It’s done well but problem is that after I download and extract this folder then all path folder also become my code is:
$id = $row['id'];
$doc_name = $row['doc_name'];
$file_names = explode(',',$doc_name);
$file_path = $_ROOT_REQUIRE."uploads/document/";
$archive_file_name = "demo.zip";
$zip = new ZipArchive($archive_file_name);
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE ) !== TRUE) {
echo "cannot open <$archive_file_name>\n";
exit("cannot open <$archive_file_name>\n");
}
foreach ($file_names as $files) {
if ($files !== '') {
$zip->addFile("$files", basename($files));
}
}
$zip->close();
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($archive_file_name).'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($archive_file_name));
header('Cache-Control: private');
ob_clean();
flush();
readfile(basename($archive_file_name));
exit;
Your Code look's is Fine.
Just Replace Your Foreach Loop .
foreach ($files as $file)
{
$file = str_replace('\\', '/', $file);
if(filetype($file) == 'file') {
$zip->addFile( $file, pathinfo( $file, PATHINFO_BASENAME ) );
}
}
it should be work
Thanks
A bit unclear on why this would be happening, looking at this line:
$zip->addFile("$files", basename($files));
Why are there " quotes around $files? I would recommend changing that to:
$zip->addFile($files, basename($files));
These are the changes I made and it work well now. Thanks to all.
$overwrite = true;
if($zip->open($archive_file_name,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true)
This larger piece:
foreach ($file_names as $file) {
$files = $file_path.$file;
$files = str_replace('\\', '/', $files);
if(filetype($files) == 'file') {
$zip->addFile( $files, pathinfo( $files, PATHINFO_BASENAME ) );
}
}

Categories