Stream_get_contents


#1

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?


#2

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.


#3

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


#4

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

http://docs.guzzlephp.org/en/latest/request-options.html#stream

$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) {
	    ob_start();
        echo sprintf("%x\r\n%s\r\n", strlen($buffer), $buffer);
        ob_end_flush();
        //10 milliseconds
        usleep(10 * 1000);
    }

    fclose($file);

    // Stop slim to handle the response
    exit;
});

#5

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


#6

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.


#7

@odan thank you for response