Yii2 generate zip file and download- In YII2.0 - php

I have a situation, I have list of user data, in that data details, i have stored a file also.
Now i want to download all the file of users in zip file, when a user click on a button like DOWNLOAD.
i have written a action in controller where im fetching the file to be downloaded, but im unable to write code for making zip finle and download it.
Below is my code in controller.
public function actionMain($jid)
{
$values = UserRequest::find()->where(['sender_code'=>$jid,'status'=>1])->all();
$i=1; foreach($values as $data) {
$users = Users::find()->where(['access_code'=>$data->reciever_code])->one();
$file_names[]= $users->attach_cv;
}
}
This is working fine. in $file_name im fetching all the file's, But i want to download this files in a zip foder.
Please help me to solve this issue
The link provided is in core php and easily implemented in that. But how about doing the same in framework. Because i have array of file name in action. As you can see above. DO i need to write the code for generating .ZIP in the same action or any other action.

I would recommend using a ZipArchive as specified in the comment by SiZE.
That way you initiate the zipping process before you start the download.
File creation:
/**
* Generate zip file for upload
*
* #throws Exception
*/
private function createZip($files)
{
$file = 'full_path_to_file/your_file_name.zip';
$zip = new ZipArchive();
if ($zip->open($file, ZipArchive::CREATE) !== TRUE) {
throw new \Exception('Cannot create a zip file');
}
foreach($files as $file){
$zip->addFile($file[file_name], $file[local_name]);
}
$zip->close();
}
And then you can return the zip file path for download in your action

Related

ZipArchive not saving file on live server in Laravel

I have some encrypted responses that I convert to a Zip file in my Laravel application. The function below downloads the API response, saves it as a Zip file, and then extracts it while I read the folder's contents. In my local environment, it works well. However, the Zip file is not getting saved to the storage folder on the live server. No error is being shown, only an empty JSON response. Please, what could be the cause?
public function downloadZipAndExtract($publication_id, $client_id)
{
/* We need to make the API call first */
$url = $this->lp_store."clients/$client_id/publications/$publication_id/file";
$file = makeSecureAPICall($url, 'raw');
// Get file path. If file already exist, just return
$path = public_path('storage/'.$publication_id);
if (!File::isDirectory($path)) {
Storage::put($publication_id.'.zip', $file);
// Zip the content
$localArchivePath = storage_path('app/'.$publication_id.'.zip');
$zip = new ZipArchive();
if (!$zip->open($localArchivePath)) {
abort(500, 'Problems experienced while reading file.');
}
// make directory with the publication_id
// then extract everything to the directory
Storage::makeDirectory($publication_id);
$zip->extractTo(storage_path('app/public/'.$publication_id));
// Delete the zip file after extracting
Storage::delete($publication_id.'.zip');
}
return;
}
First thing I'd check is if the storage file is created and if it isn't created, create it. Then I'd look at your file permissions and make sure that the the groups and users permissions are correct and that you aren't persisting file permissions on creation. I've had many instances where the process that's creating files(or trying) is not in the proper group and there is a sticky permission on the file structure.

Where am I doing wrong in downloading a file with '.CSV' format in CodeIgniter's controller?

I am new to CodeIgniter and was working on downloading a file. However, I want to download a file that resides on my local machine, I am able to locate the file by providing the path, also the file gets downloaded with a File type, However, I want my file to be in .csv format
Here goes my Controller's download function:
public function download()
{
$state_id=$this->input->post('state'); // gets me the state-id from viw's dropdown
$this->load->helper('download'); // Load download helper
$file="C:\\Users\usernew\\Desktop\\New folder\\".$state_id.".csv";
$filename=$state_id.'.csv';
if (file_exists($file))
{
$data = file_get_contents($file); //check file exists
force_download($fileName,$data);
}
else{
echo"not working!";
}
}
Where am I going wrong?
As the force_download() function accepts the file name to be set and the data to insert into that file, as you have the data in that file already, you just need to download it. so, You should use the for_download() function like this:
force_download($file,NULL);
This will solve your problem :)

PHP ZipArchive doesn't create a zip archive. What to fix in the code?

I have an .srt file located in the files/srt/username/filename.srt directory. I need to be able to download it in the browser, but to make this possible I have to zip the file first.
I found the following code online:
function download_zip() {
if (isset($_POST['download_srt'])) {
$zip = new ZipArchive();
$zip->open("files/srt/".$_SESSION['user_name']."/".$_POST['download_srt'].".zip", ZipArchive::CREATE);
// output: files/srt/username/filename.srt.zip
$zip->addFile($_POST['download_srt']);
// output of $_POST['download_srt']: filename.srt
$zip->close();
}
}
The code is called when a submit button is pressed and the $_POST data are sent.
The function works, but no ZIP file gets created in the same directory as the original srt file. No error messages appear.
You should provide the correct path to the file to add:
$zip->addFile("files/srt/".$_SESSION['user_name']."/".$_POST['download_srt']);

yii2 Create new folder and add file to it

I'm creating Yii2 application that allows users to download tutorial and it's subtitle. Currently I can do it separately but, what I want to do is to create a new folder with the video name and include both video and subtitle file in that folder and then create a zip and give that to the user for download. but I have no idea how to do it. I can zip the files using php ZipArchive but i have no idea how to create new folder and include those two files in to it.
my download action is
public function actionDownload($id)
{
// get all videos relevan for this video id
$video = TempVideo::findOne($id);
$file = $video->path;
if (file_exists($file))
{
Yii::$app->response->sendFile($file);
}
}
helps are highly appreciated.
You could use ZipArchive
http://php.net/manual/en/zip.examples.php
or launch command line with:
system('zip filecompress.zip file1 file2 file3');
I don't have all the information but i think it need to mlook something like this:
you need to make a new directory with mkdir() (doc: http://php.net/manual/en/function.mkdir.php);
and copy the needed files with copy()
(doc:http://php.net/manual/en/function.copy.php)
public function actionDownload($id)
{
// get all videos relevan for this video id
$video = TempVideo::findOne($id);
$file = $video->path;
if (file_exists($file))
{
Yii::$app->response->sendFile($file);
$new_video_path = '/path/to/save/dir';
//create a new dir
mkdir($new_video_path);
//copy the file to a new path
copy($file,$new_video_path.'newfilename.mp4');
copy('subtitle/pathe.txt',$new_video_path.'subtitle.txt');
}
}
and after that you can create a zip file with the ZipArchive that doc can be found here: http://php.net/manual/en/class.ziparchive.php

Multiple download file using php

I am building a site that allows the user to download a set of images based on user selection. How can I have downloads of multiple files? is it possible to download more than 1 file at a time?
If it is only possible to download 1 file at a time, how can I "create" 5 files, get them zipped, and let the user download that product zip file?
Thanks
You can only do only one download at a time.
If you like to zip the files have a look at this.
You can create the files using file_put_contents().
Update
On second thought... Maybe you are able to start multiple downloads if you open a new tab/window for each file. But the browser might block those popups:
<script type="text/javascript">
window.open('download.php?name=file1','_newtab');
window.open('download.php?name=file2','_newtab');
window.open('download.php?name=file3','_newtab');
</script>
You can't download multiple files. You have to zip them and redirect the user's browers on the zip.
You could use the PHP ZIP class to suit your needs.
This code creates a zip archive for you:
<?php
function createZipFile($files = array(), $filePath){
// Check if $files we had contains files
if(is_array($files)){
// $files contains files, loop through them
foreach($files as $file){
// Does the file exist?
if(file_exists($file)){
$filesToBeZipped[] = $file;
}
}
}
if(count($filesToBeZipped)){
// Create your new zip archive
$zipArchive = new ZipArchive();
if($zipArchive->open($filePath, ZIPARCHIVE::CREATE) !== true){
return false;
}else{
foreach($filesToBeZipped as $file) {
$zipArchive->addFile($file,$file);
}
$zipArchive->close();
return file_exists($filePath);
}
}else{
return false;
}
}
$files = array(
'filename1.extension',
'/path/to/filename/filename.extension',
);
$action = createZipFile($files,'yourSampleArchive.zip');
?>
You can download a lof of zipped file formats, look at this:
http://www.php.net/manual/en/refs.compression.php
Php can only send one file at a time, but you can generate javascript code with php which calls multiple php files.

Categories