Skip to content

Commit

Permalink
BUG Setting response length directly before output (fixes #7574)
Browse files Browse the repository at this point in the history
Complying to HTTP1.1/RFC2616 in terms of when to
set 'Content-Length' in the first place
  • Loading branch information
chillu committed Sep 29, 2012
1 parent b75c4b8 commit 356a367
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
11 changes: 11 additions & 0 deletions control/Director.php
Expand Up @@ -141,6 +141,17 @@ public static function direct($url, DataModel $model) {
number_format(memory_get_peak_usage(),0)
));
} else {
// Set content length (according to RFC2616)
if(
!headers_sent()
&& $response->getBody()
&& $req->httpMethod() != 'HEAD'
&& $response->getStatusCode() >= 200
&& !in_array($response->getStatusCode(), array(204, 304))
) {
$response->fixContentLength();
}

$response->output();
}
} else {
Expand Down
11 changes: 8 additions & 3 deletions control/HTTPResponse.php
Expand Up @@ -150,9 +150,6 @@ public function isError() {

public function setBody($body) {
$this->body = $body;

// Set content-length in bytes. Use mbstring to avoid problems with mb_internal_encoding() and mbstring.func_overload
$this->headers['Content-Length'] = mb_strlen($this->body,'8bit');
}

public function getBody() {
Expand Down Expand Up @@ -248,6 +245,14 @@ public function output() {
public function isFinished() {
return in_array($this->statusCode, array(301, 302, 401, 403));
}

/**
* Set content-length in bytes. Should be called right before {@link output()}.
*/
public function fixContentLength() {
// Use mbstring to avoid problems with mb_internal_encoding() and mbstring.func_overload
$this->headers['Content-Length'] = mb_strlen($this->body,'8bit');
}

}

Expand Down
2 changes: 2 additions & 0 deletions tests/control/HTTPResponseTest.php
Expand Up @@ -15,6 +15,7 @@ public function testStatusDescriptionStripsNewlines() {

public function testContentLengthHeader() {
$r = new SS_HTTPResponse('123ü');
$r->fixContentLength();
$this->assertNotNull($r->getHeader('Content-Length'), 'Content-length header is added');
$this->assertEquals(
5,
Expand All @@ -23,6 +24,7 @@ public function testContentLengthHeader() {
);

$r->setBody('1234ü');
$r->fixContentLength();
$this->assertEquals(
6,
$r->getHeader('Content-Length'),
Expand Down

0 comments on commit 356a367

Please sign in to comment.