Return Image from Controller symfony2

Arnaud B picture Arnaud B · Jul 1, 2013 · Viewed 29.5k times · Source

I would like to know how can i return an image from the controller without any template. I would like to use it for pixel tracking in a newsletter.

I start with this code

    $image = "1px.png";
    $file =    readfile("/path/to/my/image/1px.png");
    $headers = array(
        'Content-Type'     => 'image/png',
        'Content-Disposition' => 'inline; filename="'.$file.'"');
    return new Response($image, 200, $headers);

But on the navigator i have a broken link (file not found...)

Answer

franbenz picture franbenz · Nov 25, 2015

According to the Symfony Docs when serving files you could use a BinaryFileResponse:

use Symfony\Component\HttpFoundation\BinaryFileResponse;
$file = 'path/to/file.txt';
$response = new BinaryFileResponse($file);
// you can modify headers here, before returning
return $response;

This BinaryFileResponse automatically handles some HTTP request headers and spares you from using readfile() or other file functions.