diff --git a/control/HTTPResponse.php b/control/HTTPResponse.php index daa5b763e..d52b8bc18 100755 --- a/control/HTTPResponse.php +++ b/control/HTTPResponse.php @@ -98,7 +98,7 @@ class SS_HTTPResponse { * See {@link setStatusCode()} for more information. */ function __construct($body = null, $statusCode = null, $statusDescription = null) { - $this->body = $body; + $this->setBody($body); if($statusCode) $this->setStatusCode($statusCode, $statusDescription); } @@ -150,6 +150,9 @@ class SS_HTTPResponse { 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'] = (function_exists('mb_strlen') ? mb_strlen($this->body,'8bit') : strlen($this->body)); } function getBody() { diff --git a/tests/control/HTTPResponseTest.php b/tests/control/HTTPResponseTest.php index 9524d5199..05b42cd23 100644 --- a/tests/control/HTTPResponseTest.php +++ b/tests/control/HTTPResponseTest.php @@ -13,4 +13,21 @@ class HTTPResponseTest extends SapphireTest { ); } + function testContentLengthHeader() { + $r = new SS_HTTPResponse('123ü'); + $this->assertNotNull($r->getHeader('Content-Length'), 'Content-length header is added'); + $this->assertEquals( + 5, + $r->getHeader('Content-Length'), + 'Header matches actual content length in bytes' + ); + + $r->setBody('1234ü'); + $this->assertEquals( + 6, + $r->getHeader('Content-Length'), + 'Header is updated when body is changed' + ); + } + } \ No newline at end of file