How do you zip 3 small text files and force download with Zend Framework - zend-framework

Is there a Zend Framework method to save content from 3 files (be they dynamically generated or actually exist) and force download as a file?
Similar to this question (which didn't work for me when running from inside a controller so far, despite trying a few different ways):
PHP Zip 3 small text files and force download

You can use the PHP ZIP library (you need to have that preinstalled) like that:
$zip = new ZipArchive();
if($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true){
throw new Exception('Could not create zip file ' . $filename);
die('zip fail');
}else{
$zip->addFile($file1Uri, 'file1.txt');
$zip->addFile($file2Uri, 'file2.txt');
}
$zip->close();
if(file_exists($filename)){
return true;
}else{
throw new Exception('Could not create zip file ' . $filename);
}
Deliver the ZIP file:
protected function _deliver($file, $name, $extension, $size, $mime){
header('Pragma: private');
header("Expires: -1");
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
header("Cache-Control: no-cache");
header("Content-Transfer-Encoding: binary");
header("Content-Type: " . $mime);
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $name . '.' . $extension . '"');
header("Content-Length: " . $size);
set_time_limit(0);
if(!readfile($file)){
return false;
}
}

The answer is the upvoted one on your other question. Do it from controller, then call exit after you output the zip data so don't you render the view.

Related

How to create docx file and download it using PhpWord

Hi I always got error when trying to create docx file and I want to download it directly. My browser is stuck on ERR_INVALID_RESPONSE. I'm using CodeIgniter framework by the way. Here is the code.
<?php
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Writer\Word2007;
class Test extends MY_Controller{
public function create()
{
$phpWord = new PhpWord();
$section = $phpWord->addSection();
$section->addText('Hello World!');
$file = 'HelloWorld.docx';
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("php://output");
}
}
This code is just taken from the example in the PhpWord docs, but somehow it doesn't work. No error just ERR_INVALID_RESPONSE on the browser. What did I miss?
After a couple hours digging, I finally found the solution for my problem. The problem exists because it relates to temporary folder. So what I have to do is 1. setting the path where the file temporarily saved and 2. I have to tell Phpword that it should use that path to store generated file.
$path = './uploads/tmp'; // Set the temporary path
\PhpOffice\PhpWord\Settings::setTempDir($path); // Tell Phpword where the temporary path is
So this is the complete code
<?php
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\Writer\Word2007;
class Test extends MY_Controller{
public function create()
{
$phpWord = new PhpWord();
$section = $phpWord->addSection();
$section->addText('Hello World!');
$path = './uploads/tmp'; // Set the temporary path
\PhpOffice\PhpWord\Settings::setTempDir($path); // Tell Phpword where the temporary path is
$file = 'HelloWorld.docx';
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="' . $file . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("php://output");
}
}
Hope it can help those who get the same problem

Send file to Restful service in codeception

I would like to test restful API test for file uploading.
I try to run:
$I->sendPOST($this->endpoint, $postData, ['file' => 'example.jpg']);
and I would like it to behave the same as user sent example.jpg file in file input with name file but it doesn't seem to work this way. I'm getting:
[PHPUnit_Framework_ExceptionWrapper] An uploaded file must be an array or an instance of UploadedFile.
Is it possible to upload file using REST plugin in codeception? Documentation is very limited and it's hard to say how to do it.
I'm also testing API using Postman plugin to Google Chrome and I can upload file without a problem using this plugin.
I was struggling with the same problem recently and found out that there is another way to solve the issue without using Symfony's UploadedFile class. You only need to pass the array with file data in the same format as if it were the $_FILES array. For example, this code works perfectly well for me:
$I->sendPOST(
'/my-awesome-api',
[
'sample-field' => 'sample-value',
],
[
'myFile' => [
'name' => 'myFile.jpg',
'type' => 'image/jpeg',
'error' => UPLOAD_ERR_OK,
'size' => filesize(codecept_data_dir('myFile.jpg')),
'tmp_name' => codecept_data_dir('myFile.jpg'),
]
]
);
Hope this helps someone and prevents from inspecting the framework's source code (which I was forced to do, as the docs skip such an important detail)
After testing it seems to make it work we need to use UploadedFile object as file.
For example:
$path = codecept_data_dir();
$filename = 'example-image.jpg';
// copy original test file to have at the same place after test
copy($path . 'example.jpg', $path . $filename);
$mime = 'image/jpeg';
$uploadedFile = new \Symfony\Component\HttpFoundation\File\UploadedFile($path . $filename, $filename, $mime,
filesize($path . $filename));
$I->sendPOST($this->endpoint, $postData, ['file' => $uploadedFile]);
['file' => 'example.jpg'] format works too, but the value must be a correct path to existing file.
$path = codecept_data_dir();
$filename = 'example-image.jpg';
// copy original test file to have at the same place after test
copy($path . 'example.jpg', $path . $filename);
$I->sendPOST($this->endpoint, $postData, ['file' => $path . $filename]);
The below worked for myself,
On server:
$uploadedResume= $_FILES['resume_uploader'];
$outPut = [];
if (isset($uploadedResume) && empty($uploadedResume['error'])) {
$uploadDirectory = 'uploads/users/' . $userId . '/documents/';
if (!is_dir($uploadDirectory)) {
#mkdir($uploadDirectory, 0777, true);
}
$ext = explode('.', basename($uploadedResume['name']));
$targetPath = $uploadDirectory . md5(uniqid()) . '.' . end($ext);
if (move_uploaded_file($uploadedResume['tmp_name'], $targetPath)) {
$outPut[] = ['success' => 'success', 'uploaded_path' => $targetPath];
}
}
return json_encode($output);
Sorry for the long description code :P
On Testing side:
//resume.pdf is copied in to tests/_data directory
$I->sendPOST('/student/resume', [], ['resume_uploader' => codecept_data_dir('resume.pdf') ]);
#Yaronius's answer worked for me after I removed the following header from my test:
$I->haveHttpHeader('Content-Type', 'multipart/form-data');

How download application in zendframe work

I am using zend frame works . I want to include file download section in my application. I am using this code
> header('Content-Type: application/doc'); header('Pragma: no-cache');
> header('Content-Disposition: attachment; filename="'.$resume.'"');
> readfile(RESUME_PATH_WS . $resume);
But this code is not working .It return file with 0byte . Please help me how to i download files in zend frame work
public function downloadAction() {
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$filename = $this->_request->getParam('filename');
$filePath = folder/path to file/ . $filename;
if (file_exists($filePath)) {
$fileName = basename($filePath);
$fileSize = filesize($filePath);
header("Cache-Control: private");
header("Content-Type: application/stream");
header("Content-Length: " . $fileSize);
header("Content-Disposition: attachment; filename=" . $fileName);
readfile($filePath);
exit();
} else {
die('The provided file path is not valid.');
}
}
Simply in your html side
Download

How Upload file using Mojolicious?

I have been trying out Mojolicious web framework based on perl. And I have try to develop a full application instead of the Lite. The problem I am facing is that I am trying to upload files to server, but the below code is not working.
Please guide me what is wrong with it. Also, if the file gets uploaded then is it in public folder of the application or some place else.
Thanks in advance.
sub posted {
my $self = shift;
my $logger = $self->app->log;
my $filetype = $self->req->param('filetype');
my $fileuploaded = $self->req->upload('upload');
$logger->debug("filetype: $filetype");
$logger->debug("upload: $fileuploaded");
return $self->render(message => 'File is not available.')
unless ($fileuploaded);
return $self->render(message => 'File is too big.', status => 200)
if $self->req->is_limit_exceeded;
# Render template "example/posted.html.ep" with message
$self->render(message => 'Stuff Uploaded in this website.');
}
(First, you need some HTML form with method="post" and enctype="multipart/form-data", and a input type="file" with name="upload". Just to be sure.)
If there were no errors, $fileuploaded would be a Mojo::Upload. Then you could check its size, its headers, you could slurp it or move it, with $fileuploaded->move_to('path/file.ext').
Taken from a strange example.
To process uploading files you should use $c->req->uploads
post '/' => sub {
my $c = shift;
my #files;
for my $file (#{$c->req->uploads('files')}) {
my $size = $file->size;
my $name = $file->filename;
push #files, "$name ($size)";
$file->move_to("C:\\Program Files\\Apache Software Foundation\\Apache24\\htdocs\\ProcessingFolder\\".$name);
}
$c->render(text => "#files");
} => 'save';
See full code here: https://stackoverflow.com/a/28605563/4632019
You can use Mojolicious::Plugin::RenderFile
Mojolicious::Plugin::RenderFile

ZEND - Issue with download file (encoding, not able to open downloaded file)

I made a download form in my project, but problem is when i download the file and im trying to open it, Zend renderer is adding to it my layout html code... I read that i have to disable renderer and layout. But the problem is tjat i have to do this in my own helper, not in controller file, cause i need to have download in that helper file.
My download function is something like this:
<?php
class Zend_View_Helper_EditArticles extends Zend_View_Helper_Abstract
{
public function EditArticles()
{
//some code here, getting data from db table
//and now the download
if (isset($_POST['downloadarticle' . $i])) {
//this is probably bad and its not working as it should
//(?)Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
//(?)Zend_Controller_Action_HelperBroker::getStaticHelper('layout')->disableLayout();
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/articles/';
$file = $articles->GetArticleToDownload($_POST['art_id' . $i]);
$name = $file['name'];
$path = $file['path'];
$getfile = str_replace('//', '/', $targetPath) . $path . '.pdf';
$size = $file['size'];
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Disposition: attachment; filename=$name.pdf");
header("Content-length: $size");
header('Content-Transfer-Encoding: binary');
readfile($getfile);
break;
}
}
echo $this->view->partial('/index/index.phtml','EditArticles');
And when I download the PDF, Adobe Reader can't open it (when I download other files they can't be opened either). I opened them with notepad and before the PDF content there was a lot of HTML layout code... What am I doing wrong?
In Adobe Reader I get this message:
Adobe Reader could not open 'filename.pdf' because it is either not a supported file type or because the file has been damaged for example, it was sent as an email attachment and wasn't correctly decoded).
That code does not belong in a view helper. It belongs in the controller or maybe an action helper.
Something like this in your controller should work:
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
// ...
$this->getResponse()
->setHeader('Content-Description', 'File Transfer', true)
->setHeader('Content-Type', 'application/pdf', true) // change to application/pdf
->setHeader('Content-Disposition', "attachment; filename={$name}.pdf", true)
->setHeader('Content-length', $size, true)
->setHeader('Content-Transfer-Encoding', 'binary', true)
->appendBody(readfile($getfile));
The following 2 lines of code should accomplish what you need and do it in a fashion that works from anywhere in your Zend application.
Zend_Layout::getMvcInstance()->disableLayout();
Zend_Controller_Front::getInstance()->setParam('noViewRenderer', true);