Forcing a file to download using the Silex PHP framework


Posted by Andrew McCombe on Wed Jan 2, 2013

I’ve just been searching for a way to force a file to download using the Silex PHP framework and didn’t find any examples. After reading through the Silex code I worked it out. Here’s how to force a file to download using Silex:

$app->match('/export', function() use($app) {
    /**
     * create the file and save to disk
     */

    $stream = function () use ($file) {
        readfile($file);
    };

    return $app->stream($stream, 200, array(
        'Content-Type' => 'text/csv',
        'Content-length' => filesize($file),
        'Content-Disposition' => 'attachment; filename="file-download.csv"' 
        ));
}