using swift mailer of symfony 2, got an email but getting unnecessary response in email - symfony

getting this response by email "HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: text/html; charset=UTF-8 Date: Tue, 13 Nov 2012 04:56:14 GMT".
here is my code:
public function sendEmail($subject, $template, $templateParams)
{
$userEmail = $this->session->get('email');
$name = $this->session->get('name');
$adminEmail = $this->container;
$templateParams['username'] = $name;
$message = \Swift_Message::newInstance()
->setSubject($subject)
->setFrom($adminEmail)
->setTo($userEmail)
->setBody($this->templating->render('SocialDonSocialBundle:Email:'.$template,$templateParams), 'text/html');
$this->mailer->send($message);
Also note that this method is belongs to a service namely "Email". I have created a service "Email " which responsible to send emails. Does anybody know what might be the issue??

You need to use renderView() instead of render(), because render() always display the header.

In newer versions of Symfony2 like version 2.5.*
The solution is to use renderResponse and do a getContent() on it :
$content = $this->container->get('templating')->renderResponse(
'YOUR_TEMPLATE.twig',
templateParams)
)->getContent();
or with the same values like in the question :
$this->templating->renderResponse('SocialDonSocialBundle:Email:'.$template,$templateParams)->getContent();

Related

Symfony is adding to file size when downloading from controller

I have uploaded an image with the VichUploaderBundle am returning an image file like so:
/**
* Show license image.
*
* #param Request $request
* #return Response
*/
public function showImageAction(Request $request,$id)
{
$em = $this->getDoctrine()->getManager();
$license = $em->getRepository('MyCarBundle:License')->findOneById($id);
$fileName = $license->getFrontName();
$user = $this->getUser();
$contents = '';
$filePath = __DIR__ . '/../../../../app/uploads/licenses/'. $user->getId().'/'.$fileName;
$response = new Response();
$disposition = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $fileName);
$response->headers->set('Content-Disposition', $disposition);
$response->headers->set('Content-Type', 'image/jpg');
$response->setContent(file_get_contents($filePath));
return $response;
}
and in html im trying to show the image, like so
<img class="img-fluid w-100 u-block-hover__main--zoom-v1" src="{{ path('license_show_image',{'id':license.id}) }}" alt="Image Description">
The image was uploaded succesfully. When I open the image in the uploaded folder, it is showing fine.
But the image is not showing in the browser. while directly accessing the url, the image is downloading but it is not able to open. It is giving me the following error:
The file “ODL_Eng_Full_Back-5.jpg” could not be opened.
Does anyone know whats going on?
UPDATE:
Symfony is adding ~700kb to the file size when downloading. after uploading it seems to have proper file size, but downloading adds file size. whats going on here?
UPDATE 2:
these are the headers:
Request URL:http://localhost/app-temp/web/app_dev.php/account/license/2/show-image
Request Method:GET
Status Code:200 OK
Remote Address:[::1]:80
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Cache-Control:no-cache, private
Connection:Keep-Alive
Content-Disposition:inline; filename="ODL_Eng_Full_Back.jpg"
Content-Type:image/jpg
Date:Tue, 17 Oct 2017 23:31:02 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.27 (Unix) PHP/7.1.8
Transfer-Encoding:chunked
X-Debug-Token:0e53c1
X-Debug-Token-Link:http://localhost/app-temp/web/app_dev.php/_profiler/0e53c1
X-Powered-By:PHP/7.1.8
Request Headers
view source
Accept:image/webp,image/apng,image/*,*/*;q=0.8
Accept-Encoding:gzip, deflate, br
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Connection:keep-alive
Cookie:__atuvc=54%7C42; _ga=GA1.1.1906437920.1508087850; _gid=GA1.1.1258608977.1508087850; PHPSESSID=iuhk0pr0oqtaje5371fp7q7vfk
Host:localhost
Referer:http://localhost/app-temp/web/app_dev.php/account/creditcards/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36
You can use BinaryFileResponse (doc
) like:
$response = new BinaryFileResponse($filepath);
$response->headers->set('Content-disposition', sprintf('filename=%s', basename($filepath)));
return $response;
EDIT : HTTP Response seems to be correct.
Since you're using VichUploaderBundle, why not just use its helpers ?
<img src="{{ vich_uploader_asset(license, 'frontName') }}" alt="{{ license.frontName }}">

Symfony2. I can't set Content-Length header

i am new on Simfony and I am trying to set a Content-Length header in my response.
This is my controller action:
public function homepageAction() {
$content= $this>renderView('AcmeBlogBundle:Pages/homepage:homepage_content.html.twig');
$response= new Response();
$response->setContent($content);
$response->headers->set('Content-Length: 1736233495'); // value added manually
return $response;
} // homepage
i obtain an error 500 internal server error.
Did you try to $response->headers->set('Content-Length', 1736233495); ?
EDIT : Documentation
Maybe the "-" missing in the "$this>renderView" part ?

Process Ajax file upload with Symfony2

I used to have a ZF controller that was processing a fineuploader ajax upload. The code was simple:
$adapter = new Zend_File_Transfer_Adapter_Http();
$filename = uniqid();
$adapter->addFilter('Rename', APPLICATION_PATH . "/../public/temp-images/" . $filename);
$adapter->addValidator('Size', false, array("max" => "2MB"));
$adapter->addValidator('isImage', false);
if ($adapter->receive()) {
// Get mime type
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, APPLICATION_PATH . "/../public/temp-images/" . $filename);
finfo_close($finfo);
preg_match('/(.*)\/(.*)/', $mimeType, $matches);
$extension = '.' . $matches[2];
Now I'm refactoring using Symfony2 and I have difficulties doing the same thing. This is what I have so far:
$form = $this->createFormBuilder()
->add('qqfile', 'file', array('constraints' => new File(array('maxSize' => '2M'))))
->getForm();
if ($form->isValid()) {
die('yes');
} else {
die('no');
}
This is what gets sent from the browser:
------WebKitFormBoundaryYPzt2RqJ6W4awSFp Content-Disposition: form-data; name="qquuid"
b977c4b2-0edb-486b-aa86-4558275598aa
------WebKitFormBoundaryYPzt2RqJ6W4awSFp Content-Disposition: form-data; name="qqtotalfilesize"
14092
------WebKitFormBoundaryYPzt2RqJ6W4awSFp Content-Disposition: form-data; name="qqfile"; filename="ae35e28.png" Content-Type:
image/png
------WebKitFormBoundaryYPzt2RqJ6W4awSFp--
Now, I know for sure that the form will not be validated, because the POSTed data contains no name for the form. Actually, I don't even need to validate the whole form, just the uploaded file (like here Symfony2: upload a file using a file upload plugin), but how do I use validation for it?
I eventually figured it out myself.
Instead of using a form without a class, I created a class form whose getName() method returns an empty string. I set mapped=false for all the other fields except qqfile and also disabled the csrf protection for the form. In this way, the form gets properly submitted and the file input validated.

Additional mailer service to use the spool and send instant emails in Symfony2 - strange headers

by default I use spool mailing solution for sending newsletter in my web page. But I also need to send email immediately. So I have used this solution
If I send newsletter with Spool everything is fine. But when I use
$mailer = $this->get('instant_mailer');
I receive email with some text prepend at the beginning:
HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: text/html; charset=UTF-8 Date: Fri, 07 Sep 2012 16:19:06 GMT
How to remove this?
I bet that you're trying to send a Response object.
new Response();
it goes to __toString ()
public function __toString()
{
$this->prepare();
return
sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
$this->headers."\r\n".
$this->getContent();
}
It is because:
$this->render('template.html.twig');
returns Response to avoid that use:
$response = $this->render('template.html.twig');
$text = $response->getContent();
Regards,
Max
Use
$content = $this->renderView('template.html.twig');
instead of
$content = $this->render('template.html.twig');
render returns a response
Other posible solution to the problem is to use templating service instead of $this->render():
<?php
$body = $this->get('templating')->render('template.html.twig');

Why this json Symfony output outputs the headers

This is my first day to have fun with Symfony and drupal 8, so please excuse me if my question is very obvious.
With drupal 7:
drupal_json_output(array('products' => array_values($products)));
exit;
the json output is clean:
{"products":["item_1","item_2",....]}
With drupal 8:
use Symfony\Component\HttpFoundation\JsonResponse;
// some process
print new JsonResponse(array('products' => array_values($products)));
exit;
It outputs with the headers:
HTTP/1.0 200 OK
Cache-Control: no-cache
Content-Type: application/json
Date: Wed, 18 Jul 2012 07:53:26 GMT
{"products":["item_1","item_2",....]}
How do you get rid of those headers?
I am stuck to read the reference here.
Any hint is very much appreciated.
You can get only the "content" of a response by calling $response->getContent().
In your case you could do
use Symfony\Component\HttpFoundation\JsonResponse;
// some process
$response = new JsonResponse(array('products' => array_values($products)));
print $response->getContent();
exit;
However, be aware that this would be a bad practice because you would lose the response headers in the process, and wouldn't tell for example, what the content-type of you response is (in this case: "application/json") etc ...
I do not know how to do this properly with drupal, any tips is appreciated.

Resources