4
* This file is part of the Nette Framework (http://nette.org)
6
* Copyright (c) 2004 David Grudl (http://davidgrudl.com)
8
* For the full copyright and license information, please view
9
* the file license.txt that was distributed with this source code.
23
* @property-read bool $sent
24
* @property-read array $headers
26
final class Response extends Nette\Object implements IResponse
28
/** @var bool Send invisible garbage for IE 6? */
29
private static $fixIE = TRUE;
31
/** @var string The domain in which the cookie will be available */
32
public $cookieDomain = '';
34
/** @var string The path in which the cookie will be available */
35
public $cookiePath = '/';
37
/** @var string Whether the cookie is available only through HTTPS */
38
public $cookieSecure = FALSE;
40
/** @var string Whether the cookie is hidden from client-side */
41
public $cookieHttpOnly = TRUE;
43
/** @var int HTTP response code */
44
private $code = self::S200_OK;
47
public function __construct()
49
if (PHP_VERSION_ID >= 50400) {
50
if (is_int(http_response_code())) {
51
$this->code = http_response_code();
53
header_register_callback($this->removeDuplicateCookies);
59
* Sets HTTP response code.
62
* @throws Nette\InvalidArgumentException if code is invalid
63
* @throws Nette\InvalidStateException if HTTP headers have been sent
65
public function setCode($code)
69
if ($code < 100 || $code > 599) {
70
throw new Nette\InvalidArgumentException("Bad HTTP response '$code'.");
72
} elseif (headers_sent($file, $line)) {
73
throw new Nette\InvalidStateException("Cannot set HTTP code after HTTP headers have been sent" . ($file ? " (output started at $file:$line)." : "."));
77
$protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1';
78
header($protocol . ' ' . $code, TRUE, $code);
85
* Returns HTTP response code.
88
public function getCode()
95
* Sends a HTTP header and replaces a previous one.
96
* @param string header name
97
* @param string header value
99
* @throws Nette\InvalidStateException if HTTP headers have been sent
101
public function setHeader($name, $value)
103
if (headers_sent($file, $line)) {
104
throw new Nette\InvalidStateException("Cannot send header after HTTP headers have been sent" . ($file ? " (output started at $file:$line)." : "."));
107
if ($value === NULL && function_exists('header_remove')) {
108
header_remove($name);
109
} elseif (strcasecmp($name, 'Content-Length') === 0 && ini_get('zlib.output_compression')) {
110
// ignore, PHP bug #44164
112
header($name . ': ' . $value, TRUE, $this->code);
120
* @param string header name
121
* @param string header value
123
* @throws Nette\InvalidStateException if HTTP headers have been sent
125
public function addHeader($name, $value)
127
if (headers_sent($file, $line)) {
128
throw new Nette\InvalidStateException("Cannot send header after HTTP headers have been sent" . ($file ? " (output started at $file:$line)." : "."));
131
header($name . ': ' . $value, FALSE, $this->code);
137
* Sends a Content-type HTTP header.
138
* @param string mime-type
139
* @param string charset
141
* @throws Nette\InvalidStateException if HTTP headers have been sent
143
public function setContentType($type, $charset = NULL)
145
$this->setHeader('Content-Type', $type . ($charset ? '; charset=' . $charset : ''));
151
* Redirects to a new URL. Note: call exit() after it.
153
* @param int HTTP code
155
* @throws Nette\InvalidStateException if HTTP headers have been sent
157
public function redirect($url, $code = self::S302_FOUND)
159
$this->setCode($code);
160
$this->setHeader('Location', $url);
161
echo "<h1>Redirect</h1>\n\n<p><a href=\"" . htmlSpecialChars($url, ENT_IGNORE | ENT_QUOTES) . "\">Please click here to continue</a>.</p>";
166
* Sets the number of seconds before a page cached on a browser expires.
167
* @param string|int|DateTime time, value 0 means "until the browser is closed"
169
* @throws Nette\InvalidStateException if HTTP headers have been sent
171
public function setExpiration($time)
173
if (!$time) { // no cache
174
$this->setHeader('Cache-Control', 's-maxage=0, max-age=0, must-revalidate');
175
$this->setHeader('Expires', 'Mon, 23 Jan 1978 10:00:00 GMT');
179
$time = Nette\DateTime::from($time);
180
$this->setHeader('Cache-Control', 'max-age=' . ($time->format('U') - time()));
181
$this->setHeader('Expires', self::date($time));
187
* Checks if headers have been sent.
190
public function isSent()
192
return headers_sent();
197
* Return the value of the HTTP header.
202
public function getHeader($header, $default = NULL)
205
$len = strlen($header);
206
foreach (headers_list() as $item) {
207
if (strncasecmp($item, $header, $len) === 0) {
208
return ltrim(substr($item, $len));
216
* Returns a list of headers to sent.
219
public function getHeaders()
222
foreach (headers_list() as $header) {
223
$a = strpos($header, ':');
224
$headers[substr($header, 0, $a)] = (string) substr($header, $a + 2);
231
* Returns HTTP valid date format.
232
* @param string|int|DateTime
235
public static function date($time = NULL)
237
$time = Nette\DateTime::from($time);
238
$time->setTimezone(new \DateTimeZone('GMT'));
239
return $time->format('D, d M Y H:i:s \G\M\T');
246
public function __destruct()
248
if (self::$fixIE && isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE ') !== FALSE
249
&& in_array($this->code, array(400, 403, 404, 405, 406, 408, 409, 410, 500, 501, 505), TRUE)
250
&& $this->getHeader('Content-Type', 'text/html') === 'text/html'
252
echo Nette\Utils\Strings::random(2e3, " \t\r\n"); // sends invisible garbage for IE
253
self::$fixIE = FALSE;
260
* @param string name of the cookie
261
* @param string value
262
* @param string|int|DateTime expiration time, value 0 means "until the browser is closed"
268
* @throws Nette\InvalidStateException if HTTP headers have been sent
270
public function setCookie($name, $value, $time, $path = NULL, $domain = NULL, $secure = NULL, $httpOnly = NULL)
272
if (!headers_sent() && ob_get_level() && ob_get_length()) {
273
trigger_error("Possible problem: you are sending a cookie while already having some data in output buffer. This may not work if the outputted data grows. Try starting the session earlier.", E_USER_NOTICE);
276
if (headers_sent($file, $line)) {
277
throw new Nette\InvalidStateException("Cannot set cookie after HTTP headers have been sent" . ($file ? " (output started at $file:$line)." : "."));
283
$time ? Nette\DateTime::from($time)->format('U') : 0,
284
$path === NULL ? $this->cookiePath : (string) $path,
285
$domain === NULL ? $this->cookieDomain : (string) $domain,
286
$secure === NULL ? $this->cookieSecure : (bool) $secure,
287
$httpOnly === NULL ? $this->cookieHttpOnly : (bool) $httpOnly
290
$this->removeDuplicateCookies();
296
* Removes duplicate cookies from response.
299
public function removeDuplicateCookies()
301
if (headers_sent($file, $line) || ini_get('suhosin.cookie.encrypt')) {
306
foreach (headers_list() as $header) {
307
if (preg_match('#^Set-Cookie: .+?=#', $header, $m)) {
308
$flatten[$m[0]] = $header;
309
header_remove('Set-Cookie');
312
foreach (array_values($flatten) as $key => $header) {
313
header($header, $key === 0);
320
* @param string name of the cookie.
325
* @throws Nette\InvalidStateException if HTTP headers have been sent
327
public function deleteCookie($name, $path = NULL, $domain = NULL, $secure = NULL)
329
$this->setCookie($name, FALSE, 0, $path, $domain, $secure);