Serving Multiple File Types with AWS through SlimPHP

Ok, I recently ran into something where I wanted to implement API downloads using SlimPHP with a direct link (or id). The files are actually served through Amazon S3.

Now, the good thing is that if you are using SlimPHP version 3, it takes the Guzzle interface for the response which you can easily drop right in (with immutable of course). So what does this look like?

$app->get('/documentdownload/{directLink}', function(Request $request, Response $response) {
    $directLink = $request->getAttribute('directLink');

    // Do some stuff up here to verify or whatever.

    // Setup some AWS stuff to lookup the document by id.

    $res = $client->getObject(array(
        'Bucket' => AWS_BUCKET,
        'Key' => $keyname

    $newResponse = $response->withHeader('Content-type',$res['Content-Type'])

    return $newResponse;

That’s it! I know right! This may not be so obvious to some people and it wasn’t to me at first, so I thought I would write about it here. Keep in mind, if you are serving multiple filetypes, you have to specify the header with Content-type or else you will get some binary trash as output as Slim will default to text/html.

Also, be sure to use the correct parts of the returned object. The AWS SDK for PHP returns an Aws/S3 object. The different parts of that object are what we need as the AWS SDK Body is actually a version of the StreamInterface needed by Slim.

And then, no fancy echos or print statements, just return the response. Besides, who would use print/echo/write statements within your routes anyways right? 😉