Skip to content

Commit

Permalink
bug #20289 Fix edge case with StreamedResponse where headers are sent…
Browse files Browse the repository at this point in the history
… twice (Nicofuma)

This PR was merged into the 2.7 branch.

Discussion
----------

Fix edge case with StreamedResponse where headers are sent twice

| Q             | A
| ------------- | ---
| Branch?       | 2.7
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes/no
| Fixed tickets |
| License       | MIT
| Doc PR        |

If you have PHPs output buffering enabled (`output_buffering=4096` in your php.ini per example), there is an edge case with the StreamedResponse object where the headers are sent twice. Even if it is harmless most of the time, it can be critical sometimes (per example, if an `Access-Control-Allow-Origin` header is duplicated the browser will block the request).

Explanation: because the streamed response may need the request in order to generate the content, the `StreamedResponseListener` class calls the send method of the `Response` when the event `kernel.response` is fired. To prevent the content from being duplicated, a state has been introduced in the `sendContent()` method and it works fine.

But there is an edge case is the headers of the response. If the content generated by the `sendContent()` method is smaller than the value defined for `output_buffering` in the `php.ini` then the buffer won't be flushed and the `headers_sent()` function will return false.
Therefore when `$response->send()` is called for the second time (in the `app.php` file), the headers will be sent a second time.

Commits
-------

a79991f Fix edge case with StreamedResponse where headers are sent twice
  • Loading branch information
fabpot committed Oct 24, 2016
2 parents 7b56cc0 + a79991f commit 6bca8af
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions src/Symfony/Component/HttpFoundation/StreamedResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class StreamedResponse extends Response
{
protected $callback;
protected $streamed;
private $headersSent;

/**
* Constructor.
Expand All @@ -44,6 +45,7 @@ public function __construct($callback = null, $status = 200, $headers = array())
$this->setCallback($callback);
}
$this->streamed = false;
$this->headersSent = false;
}

/**
Expand Down Expand Up @@ -75,6 +77,22 @@ public function setCallback($callback)
$this->callback = $callback;
}

/**
* {@inheritdoc}
*
* This method only sends the headers once.
*/
public function sendHeaders()
{
if ($this->headersSent) {
return;
}

$this->headersSent = true;

parent::sendHeaders();
}

/**
* {@inheritdoc}
*
Expand Down

0 comments on commit 6bca8af

Please sign in to comment.