Previous Next

Zend_Http_Response

Introduction

Zend_Http_Response provides easy access to an HTTP responses message, as well as a set of static methods for parsing HTTP response messages. Usually, Zend_Http_Response is used as an object returned by a Zend_Http_Client request.

In most cases, a Zend_Http_Response object will be instantiated using the fromString() method, which reads a string containing an HTTP response message, and returns a new Zend_Http_Response object:

Example #1 Instantiating a Zend_Http_Response Object Using the Factory Method

$str = '';
$sock = fsockopen('www.example.com', 80);
$req =     "GET / HTTP/1.1\r\n" .
        "Host: www.example.com\r\n" .
        "Connection: close\r\n" .
        "\r\n";

fwrite($sock, $req);
while ($buff = fread($sock, 1024))
    $str .= $sock;

$response = Zend_Http_Response::fromString($str);

You can also use the contractor method to create a new response object, by specifying all the parameters of the response:

public function __construct($code, $headers, $body = null, $version = '1.1', $message = null)

  • $code: The HTTP response code (eg. 200, 404, etc.)

  • $headers: An associative array of HTTP response headers (eg. 'Host' => 'example.com')

  • $body: The response body as a string

  • $version: The HTTP response version (usually 1.0 or 1.1)

  • $message: The HTTP response message (eg 'OK', 'Internal Server Error'). If not specified, the message will be set according to the response code

Boolean Tester Methods

Once a Zend_Http_Response object is instantiated, it provides several methods that can be used to test the type of the response. These all return Boolean true or false:

  • Boolean isSuccessful(): Whether the request was successful or not. Returns TRUE for HTTP 1xx and 2xx response codes

  • Boolean isError(): Whether the response code implies an error or not. Returns TRUE for HTTP 4xx (client errors) and 5xx (server errors) response codes

  • Boolean isRedirect(): Whether the response is a redirection response or not. Returns TRUE for HTTP 3xx response codes

Example #2 Using the isError() method to validate a response

if ($response->isError()) {
  echo "Error transmitting data.\n"
  echo "Server reply was: " . $response->getStatus() .
       " " . $response->getMessage() . "\n";
}
// .. process the response here...

Accessor Methods

The main goal of the response object is to provide easy access to various response parameters.

  • int getStatus(): Get the HTTP response status code (eg. 200, 504, etc.)

  • string getMessage(): Get the HTTP response status message (eg. "Not Found", "Authorization Required")

  • string getBody(): Get the fully decoded HTTP response body

  • string getRawBody(): Get the raw, possibly encoded HTTP response body. If the body was decoded using GZIP encoding for example, it will not be decoded.

  • array getHeaders(): Get the HTTP response headers as an associative array (eg. 'Content-type' => 'text/html')

  • string|array getHeader($header): Get a specific HTTP response header, specified by $header

  • string getHeadersAsString($status_line = true, $br = "\n"): Get the entire set of headers as a string. If $status_line is true (default), the first status line (eg. "HTTP/1.1 200 OK") will also be returned. Lines are broken with the $br parameter (Can be, for example, "<br />")

  • string asString($br = "\n"): Get the entire response message as a string. Lines are broken with the $br parameter (Can be, for example, "<br />"). You can also use the magic method __toString() when casting the object as a string. It will then proxy to asString()

Example #3 Using Zend_Http_Response Accessor Methods

if ($response->getStatus() == 200) {
  echo "The request returned the following information:
"; echo $response->getBody(); } else { echo "An error occurred while fetching data:
"; echo $response->getStatus() . ": " . $response->getMessage(); }

Note: Always check return value

Since a response can contain several instances of the same header, the getHeader() method and getHeaders() method may return either a single string, or an array of strings for each header. You should always check whether the returned value is a string or array.

Example #4 Accessing Response Headers

$ctype = $response->getHeader('Content-type');
if (is_array($ctype)) $ctype = $ctype[0];

$body = $response->getBody();
if ($ctype == 'text/html' || $ctype == 'text/xml') {
  $body = htmlentities($body);
}

echo $body;

Static HTTP Response Parsers

The Zend_Http_Response class also includes several internally-used methods for processing and parsing HTTP response messages. These methods are all exposed as static methods, which means they can be used externally, even if you do not need to instantiate a response object, and just want to extract a specific part of the response.

  • int Zend_Http_Response::extractCode($response_str): Extract and return the HTTP response code (eg. 200 or 404) from $response_str

  • string Zend_Http_Response::extractMessage($response_str): Extract and return the HTTP response message (eg. "OK" or "File Not Found") from $response_str

  • string Zend_Http_Response::extractVersion($response_str): : Extract and return the HTTP version (eg. 1.1 or 1.0) from $response_str

  • array Zend_Http_Response::extractHeaders($response_str): Extract and return the HTTP response headers from $response_str as an array

  • string Zend_Http_Response::extractBody($response_str): Extract and return the HTTP response body from $response_str

  • string Zend_Http_Response::responseCodeAsText($code = null, $http11 = true): Get the standard HTTP response message for a response code $code. For example, will return "Internal Server Error" if $code is 500. If $http11 is true (default), will return HTTP/1.1 standard messages - otherwise HTTP/1.0 messages will be returned. If $code is not specified, this method will return all known HTTP response codes as an associative (code => message) array.

Apart from parser methods, the class also includes a set of decoders for common HTTP response transfer encodings:

  • string Zend_Http_Response::decodeChunkedBody($body): Decode a complete "Content-Transfer-Encoding: Chunked" body

  • string Zend_Http_Response::decodeGzip($body): Decode a "Content-Encoding: gzip" body

  • string Zend_Http_Response::decodeDeflate($body): Decode a "Content-Encoding: deflate" body

Previous Next
Introduction to Zend Framework
Overview
Installation
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Application
Introduction
Zend_Application Quick Start
Theory of Operation
Examples
Core Functionality
Available Resource Plugins
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Cache
Introduction
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
Zend_Captcha
Introduction
Captcha Operation
CAPTCHA Adapters
Zend_CodeGenerator
Introduction
Zend_CodeGenerator Examples
Zend_CodeGenerator Reference
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Zend_Controller Quick Start
Zend_Controller Basics
The Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Migrating from Previous Versions
Zend_Currency
Introduction to Zend_Currency
How to Work with Currencies
Migrating from Previous Versions
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of Dates
Constants for General Date Functions
Working Examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Db_Table_Definition
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dojo build layer support
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_Feed_Reader
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Migrating from previous versions
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Migrating from Previous Versions
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Migrating from previous versions
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Basic Usage
Advanced Usage of Zend_Json
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
API overview
Usage Scenarios
Tools
Object oriented access to the LDAP tree using Zend_Ldap_Node
Getting information from the LDAP server
Serializing LDAP data to and from LDIF
Zend_Loader
Loading Files and Classes Dynamically
The Autoloader
Resource Autoloaders
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Migrating from previous versions
Zend_Log
Overview
Writers
Formatters
Filters
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
Introduction
Pages
Containers
Migrating from Previous Versions
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction
Creating and Loading PDF Documents
Save Changes to PDF Documents
Working with Pages
Drawing
Interactive Features
Document Info and Metadata
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Queue
Introduction
Example usage
Framework
Adapters
Customizing Zend_Queue
Stomp
Zend_Reflection
Introduction
Zend_Reflection Examples
Zend_Reflection Reference
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Stroage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2: Regions and Availability Zones
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
Zend_Service_Amazon_Sqs
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Introduction
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Test_PHPUnit_Db
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Tool_Framework
Introduction
Using the CLI Tool
Architecture
Creating Providers to use with Zend_Tool_Framework
Shipped System Providers
Extending and Configuring Zend_Tool_Framework
Zend_Tool_Project
Introduction
Create A Project
Zend Tool Project Providers
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Creating source files
Additional features for translation
Plural notations for Translation
Migrating from previous versions
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Validation Messages
Zend_Version
Getting the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Migrating from Previous Versions
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Zend Framework Requirements
Introduction
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Documentation Standard
Overview
Documentation File Formatting
Recommendations
Recommended Project Structure for Zend Framework MVC Applications
Overview
Recommended Project Directory Structure
Module Structure
Rewrite Configuration Guide
Zend Framework Performance Guide
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information