From 6a1029a187ac4a01ac060f7f4a36e909672b293f Mon Sep 17 00:00:00 2001 From: Mike Cao Date: Thu, 2 Jan 2014 01:59:57 -0800 Subject: [PATCH] Response should only be sent once. --- flight/net/Response.php | 79 +++++++++++++++++++++++------------------ 1 file changed, 44 insertions(+), 35 deletions(-) diff --git a/flight/net/Response.php b/flight/net/Response.php index 90f8ce5..c31f2ee 100644 --- a/flight/net/Response.php +++ b/flight/net/Response.php @@ -29,6 +29,11 @@ class Response { */ protected $body; + /** + * @var bool If a response has already been sent + */ + protected static $sent = false; + /** * @var array HTTP status codes */ @@ -168,42 +173,40 @@ class Response { * * @return object Self reference */ - public function sendHeaders() { - if (!headers_sent()) { - // Send status code header - if (strpos(php_sapi_name(), 'cgi') !== false) { - header( - sprintf( - 'Status: %d %s', - $this->status, - self::$codes[$this->status] - ), - true - ); - } - else { - header( - sprintf( - '%s %d %s', - (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'), - $this->status, - self::$codes[$this->status]), - true, - $this->status - ); - } + public function sendHeaders() { + // Send status code header + if (strpos(php_sapi_name(), 'cgi') !== false) { + header( + sprintf( + 'Status: %d %s', + $this->status, + self::$codes[$this->status] + ), + true + ); + } + else { + header( + sprintf( + '%s %d %s', + (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'), + $this->status, + self::$codes[$this->status]), + true, + $this->status + ); + } - // Send other headers - foreach ($this->headers as $field => $value) { - if (is_array($value)) { - foreach ($value as $v) { - header($field.': '.$v, false); - } - } - else { - header($field.': '.$value); + // Send other headers + foreach ($this->headers as $field => $value) { + if (is_array($value)) { + foreach ($value as $v) { + header($field.': '.$v, false); } } + else { + header($field.': '.$value); + } } return $this; @@ -219,9 +222,15 @@ class Response { ob_end_clean(); } - $this->sendHeaders(); + if (!self::$sent) { + if (!headers_sent()) { + $this->sendHeaders(); + } + + echo $this->body; - echo $this->body; + self::$sent = true; + } return $this; }