Symfony 2: Sending a file to download from controller

Here is a snippet how to send a file to download. It creates a zip archive and sends it.

<?php

namespace Acme\DemoBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use ZipArchive;

class MyController extends Controller
    /**
     * @Route("/", name="index")
     */

    public function indexAction()
    {
        $entity = $this->getEntity();

        $index = $this->renderView('Acme:Demo:index.html.twig');
       
        $archive = new ZipArchive();
        $archive->open($this->get('kernel')->getRootDir() . '/../web/zip/' . $entity->getHash() . '.zip', ZipArchive::CREATE);
        $archive->addFromString($entity->getHash() . '.php', $index);  
       
        $response = new Response(file_get_contents($archive->filename));
       
        $d = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $entity->getHash() . '.zip');
        $response->headers->set('Content-Disposition', $d);
       
        $archive->close();
       
        return $response;
    }

Resources

HttpFoundation Component documentation: Downloading Files

Categories: Symfony
  • Ben Khalifa GHADA

    I wan’t to try this example but the error is the method getEntity() is undefined ? How I can solve this problem and thank in advance ­čśë

  • Piotr Belina

    Hi, you need to implement getEntity. It is just a sample. You can also remove it and remplace $entity->getHash() by filename.

  • Marcin Jaroszy┼äski

    Cze┼Ť─ç. Mam problem z archiwizacj─ů. Stosuj─Ö Twoje rozwi─ůzanie, ale przy pierwszym wywo┼éaniu kontrolera, wyrzuca mi b┼é─ůd

    Warning:
    file_get_contents(C:xampphtdocsmy_wwwreklamowacwebuploadsdocuments27.zip):
    failed to open stream: No such file or directory

    podczas gdy taki plik został utworzony. Jeżeli drugi raz wywołam kontroler, to ZIP jest pobierany.

    Czy m├│g┼éby co┼Ť doradzi─ç.

    Z g├│ry dzi─Ökuj─Ö.