3 * Class representing a HTTP response
\r
9 * Copyright (c) 2008-2012, Alexey Borzov <avb@php.net>
\r
10 * All rights reserved.
\r
12 * Redistribution and use in source and binary forms, with or without
\r
13 * modification, are permitted provided that the following conditions
\r
16 * * Redistributions of source code must retain the above copyright
\r
17 * notice, this list of conditions and the following disclaimer.
\r
18 * * Redistributions in binary form must reproduce the above copyright
\r
19 * notice, this list of conditions and the following disclaimer in the
\r
20 * documentation and/or other materials provided with the distribution.
\r
21 * * The names of the authors may not be used to endorse or promote products
\r
22 * derived from this software without specific prior written permission.
\r
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
\r
25 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
\r
26 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
\r
27 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
\r
28 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
\r
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
\r
30 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
\r
31 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
\r
32 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
\r
33 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
\r
34 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\r
37 * @package HTTP_Request2
\r
38 * @author Alexey Borzov <avb@php.net>
\r
39 * @license http://opensource.org/licenses/bsd-license.php New BSD License
\r
40 * @version SVN: $Id: Response.php 324936 2012-04-07 07:49:03Z avb $
\r
41 * @link http://pear.php.net/package/HTTP_Request2
\r
45 * Exception class for HTTP_Request2 package
\r
47 require_once 'HTTP/Request2/Exception.php';
\r
50 * Class representing a HTTP response
\r
52 * The class is designed to be used in "streaming" scenario, building the
\r
53 * response as it is being received:
\r
55 * $statusLine = read_status_line();
\r
56 * $response = new HTTP_Request2_Response($statusLine);
\r
58 * $headerLine = read_header_line();
\r
59 * $response->parseHeaderLine($headerLine);
\r
60 * } while ($headerLine != '');
\r
62 * while ($chunk = read_body()) {
\r
63 * $response->appendBody($chunk);
\r
66 * var_dump($response->getHeader(), $response->getCookies(), $response->getBody());
\r
70 * @package HTTP_Request2
\r
71 * @author Alexey Borzov <avb@php.net>
\r
72 * @license http://opensource.org/licenses/bsd-license.php New BSD License
\r
73 * @version Release: 2.1.1
\r
74 * @link http://pear.php.net/package/HTTP_Request2
\r
75 * @link http://tools.ietf.org/html/rfc2616#section-6
\r
77 class HTTP_Request2_Response
\r
80 * HTTP protocol version (e.g. 1.0, 1.1)
\r
88 * @link http://tools.ietf.org/html/rfc2616#section-6.1.1
\r
95 * @link http://tools.ietf.org/html/rfc2616#section-6.1.1
\r
97 protected $reasonPhrase;
\r
100 * Effective URL (may be different from original request URL in case of redirects)
\r
103 protected $effectiveUrl;
\r
106 * Associative array of response headers
\r
109 protected $headers = array();
\r
112 * Cookies set in the response
\r
115 protected $cookies = array();
\r
118 * Name of last header processed by parseHederLine()
\r
120 * Used to handle the headers that span multiple lines
\r
124 protected $lastHeader = null;
\r
130 protected $body = '';
\r
133 * Whether the body is still encoded by Content-Encoding
\r
135 * cURL provides the decoded body to the callback; if we are reading from
\r
136 * socket the body is still gzipped / deflated
\r
140 protected $bodyEncoded;
\r
143 * Associative array of HTTP status code / reason phrase.
\r
146 * @link http://tools.ietf.org/html/rfc2616#section-10
\r
148 protected static $phrases = array(
\r
150 // 1xx: Informational - Request received, continuing process
\r
152 101 => 'Switching Protocols',
\r
154 // 2xx: Success - The action was successfully received, understood and
\r
159 203 => 'Non-Authoritative Information',
\r
160 204 => 'No Content',
\r
161 205 => 'Reset Content',
\r
162 206 => 'Partial Content',
\r
164 // 3xx: Redirection - Further action must be taken in order to complete
\r
166 300 => 'Multiple Choices',
\r
167 301 => 'Moved Permanently',
\r
168 302 => 'Found', // 1.1
\r
169 303 => 'See Other',
\r
170 304 => 'Not Modified',
\r
171 305 => 'Use Proxy',
\r
172 307 => 'Temporary Redirect',
\r
174 // 4xx: Client Error - The request contains bad syntax or cannot be
\r
176 400 => 'Bad Request',
\r
177 401 => 'Unauthorized',
\r
178 402 => 'Payment Required',
\r
179 403 => 'Forbidden',
\r
180 404 => 'Not Found',
\r
181 405 => 'Method Not Allowed',
\r
182 406 => 'Not Acceptable',
\r
183 407 => 'Proxy Authentication Required',
\r
184 408 => 'Request Timeout',
\r
187 411 => 'Length Required',
\r
188 412 => 'Precondition Failed',
\r
189 413 => 'Request Entity Too Large',
\r
190 414 => 'Request-URI Too Long',
\r
191 415 => 'Unsupported Media Type',
\r
192 416 => 'Requested Range Not Satisfiable',
\r
193 417 => 'Expectation Failed',
\r
195 // 5xx: Server Error - The server failed to fulfill an apparently
\r
197 500 => 'Internal Server Error',
\r
198 501 => 'Not Implemented',
\r
199 502 => 'Bad Gateway',
\r
200 503 => 'Service Unavailable',
\r
201 504 => 'Gateway Timeout',
\r
202 505 => 'HTTP Version Not Supported',
\r
203 509 => 'Bandwidth Limit Exceeded',
\r
208 * Returns the default reason phrase for the given code or all reason phrases
\r
210 * @param int $code Response code
\r
212 * @return string|array|null Default reason phrase for $code if $code is given
\r
213 * (null if no phrase is available), array of all
\r
214 * reason phrases if $code is null
\r
215 * @link http://pear.php.net/bugs/18716
\r
217 public static function getDefaultReasonPhrase($code = null)
\r
219 if (null === $code) {
\r
220 return self::$phrases;
\r
222 return isset(self::$phrases[$code]) ? self::$phrases[$code] : null;
\r
227 * Constructor, parses the response status line
\r
229 * @param string $statusLine Response status line (e.g. "HTTP/1.1 200 OK")
\r
230 * @param bool $bodyEncoded Whether body is still encoded by Content-Encoding
\r
231 * @param string $effectiveUrl Effective URL of the response
\r
233 * @throws HTTP_Request2_MessageException if status line is invalid according to spec
\r
235 public function __construct($statusLine, $bodyEncoded = true, $effectiveUrl = null)
\r
237 if (!preg_match('!^HTTP/(\d\.\d) (\d{3})(?: (.+))?!', $statusLine, $m)) {
\r
238 throw new HTTP_Request2_MessageException(
\r
239 "Malformed response: {$statusLine}",
\r
240 HTTP_Request2_Exception::MALFORMED_RESPONSE
\r
243 $this->version = $m[1];
\r
244 $this->code = intval($m[2]);
\r
245 $this->reasonPhrase = !empty($m[3]) ? trim($m[3]) : self::getDefaultReasonPhrase($this->code);
\r
246 $this->bodyEncoded = (bool)$bodyEncoded;
\r
247 $this->effectiveUrl = (string)$effectiveUrl;
\r
251 * Parses the line from HTTP response filling $headers array
\r
253 * The method should be called after reading the line from socket or receiving
\r
254 * it into cURL callback. Passing an empty string here indicates the end of
\r
255 * response headers and triggers additional processing, so be sure to pass an
\r
256 * empty string in the end.
\r
258 * @param string $headerLine Line from HTTP response
\r
260 public function parseHeaderLine($headerLine)
\r
262 $headerLine = trim($headerLine, "\r\n");
\r
264 if ('' == $headerLine) {
\r
265 // empty string signals the end of headers, process the received ones
\r
266 if (!empty($this->headers['set-cookie'])) {
\r
267 $cookies = is_array($this->headers['set-cookie'])?
\r
268 $this->headers['set-cookie']:
\r
269 array($this->headers['set-cookie']);
\r
270 foreach ($cookies as $cookieString) {
\r
271 $this->parseCookie($cookieString);
\r
273 unset($this->headers['set-cookie']);
\r
275 foreach (array_keys($this->headers) as $k) {
\r
276 if (is_array($this->headers[$k])) {
\r
277 $this->headers[$k] = implode(', ', $this->headers[$k]);
\r
281 } elseif (preg_match('!^([^\x00-\x1f\x7f-\xff()<>@,;:\\\\"/\[\]?={}\s]+):(.+)$!', $headerLine, $m)) {
\r
282 // string of the form header-name: header value
\r
283 $name = strtolower($m[1]);
\r
284 $value = trim($m[2]);
\r
285 if (empty($this->headers[$name])) {
\r
286 $this->headers[$name] = $value;
\r
288 if (!is_array($this->headers[$name])) {
\r
289 $this->headers[$name] = array($this->headers[$name]);
\r
291 $this->headers[$name][] = $value;
\r
293 $this->lastHeader = $name;
\r
295 } elseif (preg_match('!^\s+(.+)$!', $headerLine, $m) && $this->lastHeader) {
\r
296 // continuation of a previous header
\r
297 if (!is_array($this->headers[$this->lastHeader])) {
\r
298 $this->headers[$this->lastHeader] .= ' ' . trim($m[1]);
\r
300 $key = count($this->headers[$this->lastHeader]) - 1;
\r
301 $this->headers[$this->lastHeader][$key] .= ' ' . trim($m[1]);
\r
307 * Parses a Set-Cookie header to fill $cookies array
\r
309 * @param string $cookieString value of Set-Cookie header
\r
311 * @link http://web.archive.org/web/20080331104521/http://cgi.netscape.com/newsref/std/cookie_spec.html
\r
313 protected function parseCookie($cookieString)
\r
322 if (!strpos($cookieString, ';')) {
\r
323 // Only a name=value pair
\r
324 $pos = strpos($cookieString, '=');
\r
325 $cookie['name'] = trim(substr($cookieString, 0, $pos));
\r
326 $cookie['value'] = trim(substr($cookieString, $pos + 1));
\r
329 // Some optional parameters are supplied
\r
330 $elements = explode(';', $cookieString);
\r
331 $pos = strpos($elements[0], '=');
\r
332 $cookie['name'] = trim(substr($elements[0], 0, $pos));
\r
333 $cookie['value'] = trim(substr($elements[0], $pos + 1));
\r
335 for ($i = 1; $i < count($elements); $i++) {
\r
336 if (false === strpos($elements[$i], '=')) {
\r
337 $elName = trim($elements[$i]);
\r
340 list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i]));
\r
342 $elName = strtolower($elName);
\r
343 if ('secure' == $elName) {
\r
344 $cookie['secure'] = true;
\r
345 } elseif ('expires' == $elName) {
\r
346 $cookie['expires'] = str_replace('"', '', $elValue);
\r
347 } elseif ('path' == $elName || 'domain' == $elName) {
\r
348 $cookie[$elName] = urldecode($elValue);
\r
350 $cookie[$elName] = $elValue;
\r
354 $this->cookies[] = $cookie;
\r
358 * Appends a string to the response body
\r
360 * @param string $bodyChunk part of response body
\r
362 public function appendBody($bodyChunk)
\r
364 $this->body .= $bodyChunk;
\r
368 * Returns the effective URL of the response
\r
370 * This may be different from the request URL if redirects were followed.
\r
373 * @link http://pear.php.net/bugs/bug.php?id=18412
\r
375 public function getEffectiveUrl()
\r
377 return $this->effectiveUrl;
\r
381 * Returns the status code
\r
385 public function getStatus()
\r
387 return $this->code;
\r
391 * Returns the reason phrase
\r
395 public function getReasonPhrase()
\r
397 return $this->reasonPhrase;
\r
401 * Whether response is a redirect that can be automatically handled by HTTP_Request2
\r
405 public function isRedirect()
\r
407 return in_array($this->code, array(300, 301, 302, 303, 307))
\r
408 && isset($this->headers['location']);
\r
412 * Returns either the named header or all response headers
\r
414 * @param string $headerName Name of header to return
\r
416 * @return string|array Value of $headerName header (null if header is
\r
417 * not present), array of all response headers if
\r
418 * $headerName is null
\r
420 public function getHeader($headerName = null)
\r
422 if (null === $headerName) {
\r
423 return $this->headers;
\r
425 $headerName = strtolower($headerName);
\r
426 return isset($this->headers[$headerName])? $this->headers[$headerName]: null;
\r
431 * Returns cookies set in response
\r
435 public function getCookies()
\r
437 return $this->cookies;
\r
441 * Returns the body of the response
\r
444 * @throws HTTP_Request2_Exception if body cannot be decoded
\r
446 public function getBody()
\r
448 if (0 == strlen($this->body) || !$this->bodyEncoded
\r
449 || !in_array(strtolower($this->getHeader('content-encoding')), array('gzip', 'deflate'))
\r
451 return $this->body;
\r
454 if (extension_loaded('mbstring') && (2 & ini_get('mbstring.func_overload'))) {
\r
455 $oldEncoding = mb_internal_encoding();
\r
456 mb_internal_encoding('8bit');
\r
460 switch (strtolower($this->getHeader('content-encoding'))) {
\r
462 $decoded = self::decodeGzip($this->body);
\r
465 $decoded = self::decodeDeflate($this->body);
\r
467 } catch (Exception $e) {
\r
470 if (!empty($oldEncoding)) {
\r
471 mb_internal_encoding($oldEncoding);
\r
481 * Get the HTTP version of the response
\r
485 public function getVersion()
\r
487 return $this->version;
\r
491 * Decodes the message-body encoded by gzip
\r
493 * The real decoding work is done by gzinflate() built-in function, this
\r
494 * method only parses the header and checks data for compliance with
\r
497 * @param string $data gzip-encoded data
\r
499 * @return string decoded data
\r
500 * @throws HTTP_Request2_LogicException
\r
501 * @throws HTTP_Request2_MessageException
\r
502 * @link http://tools.ietf.org/html/rfc1952
\r
504 public static function decodeGzip($data)
\r
506 $length = strlen($data);
\r
507 // If it doesn't look like gzip-encoded data, don't bother
\r
508 if (18 > $length || strcmp(substr($data, 0, 2), "\x1f\x8b")) {
\r
511 if (!function_exists('gzinflate')) {
\r
512 throw new HTTP_Request2_LogicException(
\r
513 'Unable to decode body: gzip extension not available',
\r
514 HTTP_Request2_Exception::MISCONFIGURATION
\r
517 $method = ord(substr($data, 2, 1));
\r
518 if (8 != $method) {
\r
519 throw new HTTP_Request2_MessageException(
\r
520 'Error parsing gzip header: unknown compression method',
\r
521 HTTP_Request2_Exception::DECODE_ERROR
\r
524 $flags = ord(substr($data, 3, 1));
\r
525 if ($flags & 224) {
\r
526 throw new HTTP_Request2_MessageException(
\r
527 'Error parsing gzip header: reserved bits are set',
\r
528 HTTP_Request2_Exception::DECODE_ERROR
\r
532 // header is 10 bytes minimum. may be longer, though.
\r
533 $headerLength = 10;
\r
534 // extra fields, need to skip 'em
\r
536 if ($length - $headerLength - 2 < 8) {
\r
537 throw new HTTP_Request2_MessageException(
\r
538 'Error parsing gzip header: data too short',
\r
539 HTTP_Request2_Exception::DECODE_ERROR
\r
542 $extraLength = unpack('v', substr($data, 10, 2));
\r
543 if ($length - $headerLength - 2 - $extraLength[1] < 8) {
\r
544 throw new HTTP_Request2_MessageException(
\r
545 'Error parsing gzip header: data too short',
\r
546 HTTP_Request2_Exception::DECODE_ERROR
\r
549 $headerLength += $extraLength[1] + 2;
\r
551 // file name, need to skip that
\r
553 if ($length - $headerLength - 1 < 8) {
\r
554 throw new HTTP_Request2_MessageException(
\r
555 'Error parsing gzip header: data too short',
\r
556 HTTP_Request2_Exception::DECODE_ERROR
\r
559 $filenameLength = strpos(substr($data, $headerLength), chr(0));
\r
560 if (false === $filenameLength || $length - $headerLength - $filenameLength - 1 < 8) {
\r
561 throw new HTTP_Request2_MessageException(
\r
562 'Error parsing gzip header: data too short',
\r
563 HTTP_Request2_Exception::DECODE_ERROR
\r
566 $headerLength += $filenameLength + 1;
\r
568 // comment, need to skip that also
\r
570 if ($length - $headerLength - 1 < 8) {
\r
571 throw new HTTP_Request2_MessageException(
\r
572 'Error parsing gzip header: data too short',
\r
573 HTTP_Request2_Exception::DECODE_ERROR
\r
576 $commentLength = strpos(substr($data, $headerLength), chr(0));
\r
577 if (false === $commentLength || $length - $headerLength - $commentLength - 1 < 8) {
\r
578 throw new HTTP_Request2_MessageException(
\r
579 'Error parsing gzip header: data too short',
\r
580 HTTP_Request2_Exception::DECODE_ERROR
\r
583 $headerLength += $commentLength + 1;
\r
585 // have a CRC for header. let's check
\r
587 if ($length - $headerLength - 2 < 8) {
\r
588 throw new HTTP_Request2_MessageException(
\r
589 'Error parsing gzip header: data too short',
\r
590 HTTP_Request2_Exception::DECODE_ERROR
\r
593 $crcReal = 0xffff & crc32(substr($data, 0, $headerLength));
\r
594 $crcStored = unpack('v', substr($data, $headerLength, 2));
\r
595 if ($crcReal != $crcStored[1]) {
\r
596 throw new HTTP_Request2_MessageException(
\r
597 'Header CRC check failed',
\r
598 HTTP_Request2_Exception::DECODE_ERROR
\r
601 $headerLength += 2;
\r
603 // unpacked data CRC and size at the end of encoded data
\r
604 $tmp = unpack('V2', substr($data, -8));
\r
605 $dataCrc = $tmp[1];
\r
606 $dataSize = $tmp[2];
\r
608 // finally, call the gzinflate() function
\r
609 // don't pass $dataSize to gzinflate, see bugs #13135, #14370
\r
610 $unpacked = gzinflate(substr($data, $headerLength, -8));
\r
611 if (false === $unpacked) {
\r
612 throw new HTTP_Request2_MessageException(
\r
613 'gzinflate() call failed',
\r
614 HTTP_Request2_Exception::DECODE_ERROR
\r
616 } elseif ($dataSize != strlen($unpacked)) {
\r
617 throw new HTTP_Request2_MessageException(
\r
618 'Data size check failed',
\r
619 HTTP_Request2_Exception::DECODE_ERROR
\r
621 } elseif ((0xffffffff & $dataCrc) != (0xffffffff & crc32($unpacked))) {
\r
622 throw new HTTP_Request2_Exception(
\r
623 'Data CRC check failed',
\r
624 HTTP_Request2_Exception::DECODE_ERROR
\r
631 * Decodes the message-body encoded by deflate
\r
633 * @param string $data deflate-encoded data
\r
635 * @return string decoded data
\r
636 * @throws HTTP_Request2_LogicException
\r
638 public static function decodeDeflate($data)
\r
640 if (!function_exists('gzuncompress')) {
\r
641 throw new HTTP_Request2_LogicException(
\r
642 'Unable to decode body: gzip extension not available',
\r
643 HTTP_Request2_Exception::MISCONFIGURATION
\r
646 // RFC 2616 defines 'deflate' encoding as zlib format from RFC 1950,
\r
647 // while many applications send raw deflate stream from RFC 1951.
\r
648 // We should check for presence of zlib header and use gzuncompress() or
\r
649 // gzinflate() as needed. See bug #15305
\r
650 $header = unpack('n', substr($data, 0, 2));
\r
651 return (0 == $header[1] % 31)? gzuncompress($data): gzinflate($data);
\r