Downloading files with Zend Framework - zend-framework

I'm a newbie to Zend Framework and I have such problem. On my web page I have the demos of products to be downloaded by users. When they want to download them, they have to fill the form (name, company, e-mail, contact phone) and then click Submit to start downloading. I would like them to be redirected to the product page. Here is my showFormAction code in controller:
if ($this->_request->isPost())
{
if (!$form->isValid($this->_request->getPost()))
{
//shows messages and the form again
}
else
{
$file = $this->findYoungestFile('/demo/'.$product.'/');
$this->sendFileToClient($file);
$this->_redirect('/products/'.$product);
//sending mail
$infoMail = new InfoMail($this->_request->getPost(), 'download', $product);
$this->sendInfoMails($infoMail);
}
}
else
//show form
And here is sendFileToClient function
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
The redirection doesn't work. I suppose there is a problem with headers sent to the browser, but I don't know how to solve it. Could anyone help me, please?
Thanks & regards,
Malgorzata

By the time you're trying to redirect user to another page the HTTP-headers had already sent. In other words you cannot supply a file and do a redirect at the same time. Well, at least the way you're trying to do this.

Related

Drupal email wraps path

I am sending an email from my Drupal website using the hook_mail().
My problem is that the folder where the report is saved into has spaces in its name "to keep folder" and the email's body wraps exactly in the middle of the name of that folder EX:
Please visit \\folder1\folder2\to keep
folder to see the report.
I was asked to make the "\folder1\folder2\to keep folder" internal path a link if possible or to at least force the whole path to stay on one line.
I tried the url() function like this:
$message['body'][] = 'Please visit ' . url('\\\\folder1\folder2\to keep folder') . ' to see the report.';
but still it will not show up as a link.
Here is my entire hook_mail() function:
/**
* Implements hook_mail().
*/
function my_module_mail($key, &$message, $params) {
switch ($key) {
case 'email_success':
$message['headers']['Bcc'] = 'my_email#mydomain.com';
$message['subject'] = 'Successfully generated the report';
$message['body'][] = 'The daily budget report has been generated.';
$message['body'][] = 'Please visit ' . url('\\\\folder1\folder2\to keep folder') . ' to see the report.';
break;
case 'email_fail':
// Build the other email
break;
}
}
Any ideas ?
Your emails are probably being sent in plain text. Try contrib module Mime Mail allowing you to receive emails in HTML.
Via configuration > system > mimemail, choose your preferred E-mail format & try your hook_mail again.

How can I add a picture in an email which is a html format with SwiftMailer (Symfony2)

I have developed a page for a client, and I have to do a newsletter. I already have the template of the mail and what I want is to insert a picture in those emails.
The code :
foreach($customer as $customer)
{
$mail = $customer->getMailcustomer();
$message = \Swift_Message::newInstance();
$message->setSubject('Info');
$message->setFrom('abcd#noreply.ch');
$message->setTo($mail);
$message->setContentType("text/html");
$message->setBody(
$this->renderView(
'MyBundle:Customer:email.html.twig',
array('form' => $form->createView())
)
);
$this->get('mailer')->send($message);
}
This code works and I have a nice email page but what I don't know is how to insert a picture in it.
I tried to insert a picture in the email.html.twig but it didn't work.
Here is the example from http://swiftmailer.org/docs/messages.html:
You can embed files in two stages if you prefer. Just capture the return value of embed() in a variable and use that as the src attribute.
// You can embed files from a URL if allow_url_fopen is on in php.ini
$message->setBody(
'<html>' .
' <head></head>' .
' <body>' .
' Here is an image <img src="' .
$message->embed(Swift_Image::fromPath('http://site.tld/logo.png')) .
'" alt="Image" />' .
' Rest of message' .
' </body>' .
'</html>',
'text/html'
);
Put your images on a server. Then link them with an absolute url path in the html of the newsletter. The images will simply be requested from that server.

Remove gzip encoding in Zend

Lots of questions here from people trying to implement gzip encoding in Zend - I need to do the opposite!
I have a controller which extends the standard Zend_Controller_Action. My downloadAction has a PDF file as it's response body. That works well, except that the downloaded file isn't correctly recognised by the client browsers.
The downloaded file is identified as a 'Zip Archive' by the browser download. When saved and double-clicked it opens correctly as a PDF. The response header shows Content-Encoding:gzip, so I figure that's likely the culprit.
The core of my action is:
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
if ($fd = fopen($pdfpath.$pdf->Filename,'r'))
{
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="summary.PDF"');
while(!feof($fd))
{
$buffer = fread($fd, 2048);
echo $buffer;
}
fclose($fd);
}
There is some other code before this piece, but it does nothing more exciting than populate the variables.
How would I go about disabling the Content-Encoding:gzip header for just this response, or if that's the wrong end of the stick (it would be good to use compression, but not at the expense of user experience), how do I get the client to correctly identify the downloaded file once the compression has been reversed?
I would recommend to use framework's Zend_Controller_Response_Http instead of header() function, usually I specify "default" headers with gzip compression etc. in my Bootstrap for all responses, and override them in actions for some special reasons:
public function indexAction()
{
$frontContoller = $this->getFrontController();
$this->_helper->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
$response = new Zend_Controller_Response_Http();
$response
->setHeader('Content-Type', 'application/pdf')
->setHeader('Content-Disposition', 'attachment; filename=summary.pdf')
->setHeader('Expires', ''.gmdate('D, d M Y H:i:s', strtotime('31.08.1986')) . ' GMT', true)
->setHeader('Cache-Control', 'no-cache')
->setHeader('Pragma', 'no-cache', true);
$response->setBody(file_get_contents('/full/path/to/summary.pdf'));
$frontContoller->setResponse($response);
}

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

Zend PDF - want to open instead of saving

am generating pdf using Zend_pdf
its saving after creating
I want to open it instead of saving.
When i access the url directly
Use render() method
// Set PDF headers
header ('Content-Type:', 'application/pdf');
header ('Content-Disposition:', 'inline;');
// Output pdf
echo $pdf->render();
I couldn't find a way to open a PDF directly, so I did this instead:
<?php
// Save PDF into file
$oPdf->save("./pdfcache/filename.pdf");
// Set headers
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename=filename.pdf');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
ini_set('zlib.output_compression','0');
// Get File Contents and echo to output
echo file_get_contents("./pdfcache/filename.pdf");
// Prevent anything else from being outputted
die();
It's not perfect, but it does the job for me.