3

I am trying to let the user download a file in the Slim php framework.

The intended use is that the file will be:

http://api.test.com/item/123.json <- returns json string with data

http://api.test.com/item/123.pdf <- download pdf-file with human-readable presentation of data

I have the code producing the PDF, but what I need is to make Slim send the correct headers so the file will be downloaded.

This is the following code I have (working) for the existing system:

header("Pragma: public");
header('Content-disposition: attachment; filename='.$f->name);
header('Content-type: ' .$f->type);
header('Content-Transfer-Encoding: binary');
echo $f->data;

Following is my current (non-working) Slim-code where the headers I declare is not sent to the browser. Instead I get text/html. (Note that this example only contains one header, I have also tested to see if any other header manipulation would cause any effect, but it haven't). The switch-case of json/pdf/xml will be added later on.

R::setup();    
$app = new \Slim\Slim();
$app->get('/item', function() use ($app) {
    $f = R::load('file', 123);
    $app->response->headers->set("Content-Type", "application/pdf"); //$f->type
    $app->response->setBody($f->data);

 });

$app->run();

The $app->response->setBody($f->data) however works fine.

olearos
  • 75
  • 1
  • 7
  • I can't recreate your issue in Slim 2.4.0 or 2.4.3. If you're able to use the latest version of Slim and you aren't already, I highly recommend upgrading. – Jeremy Kendall Apr 08 '14 at 04:52

1 Answers1

3

Problem solved. Turned out to be a included php class with whitespace in it. This messed up the headers i guess.

Solved by creating a new, empty project and include step by step until the bad class showed.

Working solution for setting headers inside a Slim function;

<?php

require 'vendor/autoload.php';
$app = new \Slim\Slim();

$app->get('/foo', function () use ($app) {
    $app->response->headers->set('Content-Type', "application/pdf");
    $app->response->setBody("foo");
});

$app->run();
?>

Updated: This is the headers I use to let a user download a PDF:

$app->response->headers->set('Content-Type', $f->type);
$app->response->headers->set('Pragma', "public");
$app->response->headers->set('Content-disposition:', 'attachment; filename=' . $f->name);
$app->response->headers->set('Content-Transfer-Encoding', 'binary');
$app->response->headers->set('Content-Length', $f->size);
$app->response->setBody($f->data);
olearos
  • 75
  • 1
  • 7