Hi everyone,
In slim while response preparing “$body->write($output . $response->getBody());” calling, $response->getBody() calls stream _toString method, then to string calls $this->getContents.
İn that place stream_get_contents php method calling. İf response stream body is too big, do memory problem occur here?

Most PSR-7 implementations use streams. Since the stream is held in memory, problems can occur if the requests/responses are too large. Depending on memory limit and configuration, the limit may vary.

1 Like

When sending data response send chunk by chunk, can situation in my question handle as read data from stream chunk by chunk?

You could use Guzzle to read bytes of the (response) stream until the end of the stream is reached

$response = $client->request('GET', '/stream/20', ['stream' => true]);
// Read bytes off of the stream until the end of the stream is reached
$body = $response->getBody();
while (!$body->eof()) {
    echo $body->read(1024);

Implementing a chunked response with the PSR-7 is nearly impossible. Please correct me if I’m wrong. BUT in Vanilla PHP it’s still possible.

Pseudo Slim code:

use Slim\Http\Request;
use Slim\Http\Response;

$app->get('/download', function (Request $request, Response $response) {
    set_time_limit(60 * 5);
    ini_set('max_execution_time', 60 * 5);

    header("Transfer-Encoding: chunked", true);
    header("Content-Encoding: chunked", true);
    header("Content-Type: application/pdf", true);
    header("Connection: keep-alive", true);

    $fileName = 'file.pdf';
    $file = fopen($fileName,'r');

    while (($buffer = fgets($file, 4096)) !== false) {
        echo sprintf("%x\r\n%s\r\n", strlen($buffer), $buffer);
        //10 milliseconds
        usleep(10 * 1000);


    // Stop slim to handle the response

According to my knowledge headers independent from php buffer, am I right?

The header() does indeed ignore output buffering. Part of the reason to use output buffering is so you can send HTTP headers “out of order” since the response is buffered. You can’t send HTTP headers once you’ve sent any kind of output (unless that output is buffered).

I updated my example code.

@odan thank you for response

1 Like