NoSoup4you
NoSoup4you

Reputation: 668

How can i set multiple Header Keys with Slim Framework 3

I am using the below sample code to return data to the browser

$response->write($image);
return $response->withHeader('Content-Type', 'image/jpeg');

which works fine but how would i go about it if i wanted to also return Content-Length ? the only option i found so far is to copy the response into a new object like below but i don't think that's efficient if i have a $image in the response.

$response = $response->withAddedHeader('Content-Length', strlen($image));

I tried it as array but that doesn't work..

Upvotes: 1

Views: 1239

Answers (1)

Nima
Nima

Reputation: 3409

Quoting from Slim 3 docs

Reminder
Unlike the withHeader() method, this method appends the new value to the set of values that already exist for the same header name. The Response object is immutable. This method returns a copy of the Response object that has the appended header value.

Both withHeader() and with appendedHeader() methods return a copy of the response object. So even if your do not assign the return value of $response->withHeader() to a variable and return the result directly, you are still working with a copy of the response object.

Regarding your concern about efficiency, you should use streams instead of string as response body. The following is an example of how to use streams for returning an image as the response:

<?php

use Slim\App;
use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Http\Body;

return function (App $app) {
    $container = $app->getContainer();
    $app->get('/', function(Request $request, Response $response) {
        $image = fopen('sample.jpg', 'r');
        return $response->withBody(new Body($image))
            ->withHeader('Content-Type', 'image/jpeg')
            ->withAddedHeader('Content-Length', fstat($image)['size']);
    });
};

Upvotes: 2

Related Questions