. */ /** * This file contains the HTTPResponse class. * * @author Dinu Florin * @package Modules * @subpackage Network */ /** * HTTPResponse class. * TODO: getCookies(), getCookie() * * @author Dinu Florin * @package Modules * @subpackage Network */ class HTTPResponse extends Pt { protected $headers = array(); protected $body = null; protected $status = null; protected $protocol = null; /** * Get the request headers as an array of key-value pairs of headers. * For example: array('Content-type'=>'text/plain'); * * @return array */ public function getHeaders() { return $this->headers; } /** * Get a single header. * * @param string $name The header name. * @return string The header value. * @see HTTPResponse::getHeaders() */ public function getHeader($name) { $name = HTTP::makeStdHeaderName($name); if(isset($this->headers[$name])) { return $this->headers[$name]; } else { return null; } } /** * Get status. * * @return number The status code. */ public function getStatus() { return $this->status; } /** * Get protocol. The protocol can be HTTP1_0 or HTTP1_1. * * @return number */ public function getProtocol() { return $this->protocol; } /** * Get the content of the output buffer. * * @return string */ public function getContent() { return $this->body; } /** * Constructor. * * @param string $responseString The response string. */ public function __construct($responseString) { $responseString = ltrim($responseString); $headersEnd = strpos($responseString, "\r\n\r\n"); if($headersEnd === false) { throw new NetworkException('Malformed response'); } //Parse the headers $headers = substr($responseString, 0, $headersEnd); $headers = explode("\r\n", $headers); foreach($headers as $header) { $header = explode(':', $header, 2); if(count($header) == 1) //This is the status line. { preg_match('/^HTTP\/1\.([01])\s*([0-9]{3})/i', $header[0], $matches); if(!isset($matches[1]) || !isset($matches[2])) { throw new NetworkException('Malformed response'); } $protocol = $matches[1]; $status = $matches[2]; } else //It's a normal header. { $header[0] = HTTP::makeStdHeaderName($header[0]); $header[1] = trim($header[1]); if(isset($this->headers[$header[0]])) { $this->headers[$header[0]] .= ', '.$header[1]; } else { $this->headers[$header[0]] = $header[1]; } } } $this->body = substr($responseString, $headersEnd+4); //$hend + "\r\n\r\n" unset($responseString); if(!isset($protocol) || !isset($status)) { throw new NetworkException('Malformed response'); } switch($protocol) { case '0': $this->protocol = HTTP::HTTP1_0; break; case '1': $this->protocol = HTTP::HTTP1_1; break; default: throw new NetworkException('Unsupported protocol'); } $this->status = (int)$status; } } ?>