Zend_Http_Client - Advanced Usage

Zend_Http_Client - Connection Adapters

Overview

Zend_Http_Client is based on a connection adapter design. The connection adapter is the object in charge of performing the actual connection to the server, as well as writing requests and reading responses. This connection adapter can be replaced, and you can create and extend the default connection adapters to suite your special needs, without the need to extend or replace the entire HTTP client class, and with the same interface.

Currently, the Zend_Http_Client class provides four built-in connection adapters:

  • Zend_Http_Client_Adapter_Socket (default)

  • Zend_Http_Client_Adapter_Proxy

  • Zend_Http_Client_Adapter_Curl

  • Zend_Http_Client_Adapter_Test

The Zend_Http_Client object's adapter connection adapter is set using the 'adapter' configuration option. When instantiating the client object, you can set the 'adapter' configuration option to a string containing the adapter's name (eg. 'Zend_Http_Client_Adapter_Socket') or to a variable holding an adapter object (eg. new Zend_Http_Client_Adapter_Test). You can also set the adapter later, using the Zend_Http_Client->setConfig() method.

The Socket Adapter

The default connection adapter is the Zend_Http_Client_Adapter_Socket adapter - this adapter will be used unless you explicitly set the connection adapter. The Socket adapter is based on PHP's built-in fsockopen() function, and does not require any special extensions or compilation flags.

The Socket adapter allows several extra configuration options that can be set using Zend_Http_Client->setConfig() or passed to the client constructor.

Zend_Http_Client_Adapter_Socket configuration parameters
Parameter Description Expected Type Default Value
persistent Whether to use persistent TCP connections boolean FALSE
ssltransport SSL transport layer (eg. 'sslv2', 'tls') string ssl
sslcert Path to a PEM encoded SSL certificate string NULL
sslpassphrase Passphrase for the SSL certificate file string NULL
sslusecontext Enables proxied connections to use SSL even if the proxy connection itself does not. boolean FALSE

Note: Persistent TCP Connections
Using persistent TCP connections can potentially speed up HTTP requests - but in most use cases, will have little positive effect and might overload the HTTP server you are connecting to.
It is recommended to use persistent TCP connections only if you connect to the same server very frequently, and are sure that the server is capable of handling a large number of concurrent connections. In any case you are encouraged to benchmark the effect of persistent connections on both the client speed and server load before using this option.
Additionally, when using persistent connections it is recommended to enable Keep-Alive HTTP requests as described in the configuration section - otherwise persistent connections might have little or no effect.

Note: HTTPS SSL Stream Parameters
ssltransport, sslcert and sslpassphrase are only relevant when connecting using HTTPS.
While the default SSL settings should work for most applications, you might need to change them if the server you are connecting to requires special client setup. If so, you should read the sections about SSL transport layers and options » here.

Example #1 Changing the HTTPS transport layer

  1. // Set the configuration parameters
  2. 'adapter'      => 'Zend_Http_Client_Adapter_Socket',
  3.     'ssltransport' => 'tls'
  4. );
  5.  
  6. // Instantiate a client object
  7. 'https://www.example.com', $config);
  8.  
  9. // The following request will be sent over a TLS secure connection.
  10. $response = $client->request();

The result of the example above will be similar to opening a TCP connection using the following PHP command:

fsockopen('tls://www.example.com', 443)

Customizing and accessing the Socket adapter stream context

Starting from Zend Framework 1.9, Zend_Http_Client_Adapter_Socket provides direct access to the underlying » stream context used to connect to the remote server. This allows the user to pass specific options and parameters to the TCP stream, and to the SSL wrapper in case of HTTPS connections.

You can access the stream context using the following methods of Zend_Http_Client_Adapter_Socket:

  • setStreamContext($context) Sets the stream context to be used by the adapter. Can accept either a stream context resource created using the » stream_context_create() PHP function, or an array of stream context options, in the same format provided to this function. Providing an array will create a new stream context using these options, and set it.

  • getStreamContext() Get the stream context of the adapter. If no stream context was set, will create a default stream context and return it. You can then set or get the value of different context options using regular PHP stream context functions.

Example #2 Setting stream context options for the Socket adapter

  1. // Array of options
  2. 'socket'// Bind local socket side to a specific interface
  3.         'bindto' => '10.1.2.3:50505'
  4.     ),
  5.     'ssl'// Verify server side certificate,
  6.         // do not accept invalid or self-signed SSL certificates
  7.         'verify_peer''allow_self_signed'// Capture the peer's certificate
  8.         'capture_peer_cert'// Create an adapter object and attach it to the HTTP client
  9. // Method 1: pass the options array to setStreamContext()
  10. $adapter->setStreamContext($options);
  11.  
  12. // Method 2: create a stream context and pass it to setStreamContext()
  13. // Method 3: get the default stream context and set the options on it
  14. // Now, preform the request
  15. $response = $client->request();
  16.  
  17. // If everything went well, you can now access the context again
  18. 'ssl']['peer_certificate'];

Note: Note that you must set any stream context options before using the adapter to preform actual requests. If no context is set before preforming HTTP requests with the Socket adapter, a default stream context will be created. This context resource could be accessed after preforming any requests using the getStreamContext() method.

The Proxy Adapter

The Zend_Http_Client_Adapter_Proxy adapter is similar to the default Socket adapter - only the connection is made through an HTTP proxy server instead of a direct connection to the target server. This allows usage of Zend_Http_Client behind proxy servers - which is sometimes needed for security or performance reasons.

Using the Proxy adapter requires several additional configuration parameters to be set, in addition to the default 'adapter' option:

Zend_Http_Client configuration parameters
Parameter Description Expected Type Example Value
proxy_host Proxy server address string 'proxy.myhost.com' or '10.1.2.3'
proxy_port Proxy server TCP port integer 8080 (default) or 81
proxy_user Proxy user name, if required string 'shahar' or '' for none (default)
proxy_pass Proxy password, if required string 'secret' or '' for none (default)
proxy_auth Proxy HTTP authentication type string Zend_Http_Client::AUTH_BASIC (default)

proxy_host should always be set - if it is not set, the client will fall back to a direct connection using Zend_Http_Client_Adapter_Socket. proxy_port defaults to '8080' - if your proxy listens on a different port you must set this one as well.

proxy_user and proxy_pass are only required if your proxy server requires you to authenticate. Providing these will add a 'Proxy-Authentication' header to the request. If your proxy does not require authentication, you can leave these two options out.

proxy_auth sets the proxy authentication type, if your proxy server requires authentication. Possibly values are similar to the ones accepted by the Zend_Http_Client::setAuth() method. Currently, only basic authentication (Zend_Http_Client::AUTH_BASIC) is supported.

Example #3 Using Zend_Http_Client behind a proxy server

  1. // Set the configuration parameters
  2. 'adapter'    => 'Zend_Http_Client_Adapter_Proxy',
  3.     'proxy_host' => 'proxy.int.zend.com',
  4.     'proxy_port' => 8000,
  5.     'proxy_user' => 'shahar.e',
  6.     'proxy_pass' => 'bananashaped'
  7. );
  8.  
  9. // Instantiate a client object
  10. 'http://www.example.com', $config);
  11.  
  12. // Continue working...

As mentioned, if proxy_host is not set or is set to a blank string, the connection will fall back to a regular direct connection. This allows you to easily write your application in a way that allows a proxy to be used optionally, according to a configuration parameter.

Note: Since the proxy adapter inherits from Zend_Http_Client_Adapter_Socket, you can use the stream context access method (see this section) to set stream context options on Proxy connections as demonstrated above.

The cURL Adapter

cURL is a standard HTTP client library that is distributed with many operating systems and can be used in PHP via the cURL extension. It offers functionality for many special cases which can occur for a HTTP client and make it a perfect choice for a HTTP adapter. It supports secure connections, proxy, all sorts of authentication mechanisms and shines in applications that move large files around between servers.

Example #4 Setting cURL options

  1. span style="color: #ff0000;">'adapter'   => 'Zend_Http_Client_Adapter_Curl',
  2.     'curloptions'

By default the cURL adapter is configured to behave exactly like the Socket Adapter and it also accepts the same configuration parameters as the Socket and Proxy adapters. You can also change the cURL options by either specifying the 'curloptions' key in the constructor of the adapter or by calling setCurlOption($name, $value). The $name key corresponds to the CURL_* constants of the cURL extension. You can get access to the Curl handle by calling $adapter->getHandle();

Example #5 Transfering Files by Handle

You can use cURL to transfer very large files over HTTP by filehandle.

  1. span style="color: #ff0000;">"filepath""filepath", "r"'curloptions'"PUT");

The Test Adapter

Sometimes, it is very hard to test code that relies on HTTP connections. For example, testing an application that pulls an RSS feed from a remote server will require a network connection, which is not always available.

For this reason, the Zend_Http_Client_Adapter_Test adapter is provided. You can write your application to use Zend_Http_Client, and just for testing purposes, for example in your unit testing suite, you can replace the default adapter with a Test adapter (a mock object), allowing you to run tests without actually performing server connections.

The Zend_Http_Client_Adapter_Test adapter provides an additional method, setResponse() method. This method takes one parameter, which represents an HTTP response as either text or a Zend_Http_Response object. Once set, your Test adapter will always return this response, without even performing an actual HTTP request.

Example #6 Testing Against a Single HTTP Response Stub

  1. // Instantiate a new adapter and client
  2. 'http://www.example.com''adapter' => $adapter
  3. ));
  4.  
  5. // Set the expected response
  6. $adapter->setResponse(
  7.     "HTTP/1.1 200 OK"        . "\r\n" .
  8.     "Content-type: text/xml" . "\r\n" .
  9.                                "\r\n" .
  10.     '<?xml version="1.0" encoding="UTF-8"?>' .
  11.     '<rss version="2.0" ' .
  12.     '     xmlns:content="http://purl.org/rss/1.0/modules/content/"' .
  13.     '     xmlns:wfw="http://wellformedweb.org/CommentAPI/"' .
  14.     '     xmlns:dc="http://purl.org/dc/elements/1.1/">' .
  15.     '  <channel>' .
  16.     '    <title>Premature Optimization</title>' .
  17.     // and so on...
  18.     '</rss>');
  19.  
  20. $response = $client->request('GET');
  21. // .. continue parsing $response..

The above example shows how you can preset your HTTP client to return the response you need. Then, you can continue testing your own code, without being dependent on a network connection, the server's response, etc. In this case, the test would continue to check how the application parses the XML in the response body.

Sometimes, a single method call to an object can result in that object performing multiple HTTP transactions. In this case, it's not possible to use setResponse() alone because there's no opportunity to set the next response(s) your program might need before returning to the caller.

Example #7 Testing Against Multiple HTTP Response Stubs

  1. // Instantiate a new adapter and client
  2. 'http://www.example.com''adapter' => $adapter
  3. ));
  4.  
  5. // Set the first expected response
  6. $adapter->setResponse(
  7.     "HTTP/1.1 302 Found"      . "\r\n" .
  8.     "Location: /"             . "\r\n" .
  9.     "Content-Type: text/html" . "\r\n" .
  10.                                 "\r\n" .
  11.     '<html>' .
  12.     '  <head><title>Moved</title></head>' .
  13.     '  <body><p>This page has moved.</p></body>' .
  14.     '</html>');
  15.  
  16. // Set the next successive response
  17. $adapter->addResponse(
  18.     "HTTP/1.1 200 OK"         . "\r\n" .
  19.     "Content-Type: text/html" . "\r\n" .
  20.                                 "\r\n" .
  21.     '<html>' .
  22.     '  <head><title>My Pet Store Home Page</title></head>' .
  23.     '  <body><p>...</p></body>' .
  24.     '</html>');
  25.  
  26. // inject the http client object ($client) into your object
  27. // being tested and then test your object's behavior below

The setResponse() method clears any responses in the Zend_Http_Client_Adapter_Test's buffer and sets the first response that will be returned. The addResponse() method will add successive responses.

The responses will be replayed in the order that they were added. If more requests are made than the number of responses stored, the responses will cycle again in order.

In the example above, the adapter is configured to test your object's behavior when it encounters a 302 redirect. Depending on your application, following a redirect may or may not be desired behavior. In our example, we expect that the redirect will be followed and we configure the test adapter to help us test this. The initial 302 response is set up with the setResponse() method and the 200 response to be returned next is added with the addResponse() method. After configuring the test adapter, inject the HTTP client containing the adapter into your object under test and test its behavior.

If you need the adapter to fail on demand you can use setNextRequestWillFail($flag). The method will cause the next call to connect() to throw an Zend_Http_Client_Adapter_Exception exception. This can be useful when your application caches content from an external site (in case the site goes down) and you want to test this feature.

Example #8 Forcing the adapter to fail

  1. // Instantiate a new adapter and client
  2. 'http://www.example.com''adapter' => $adapter
  3. ));
  4.  
  5. // Force the next request to fail with an exception
  6. // This call will result in a Zend_Http_Client_Adapter_Exception
  7. // ...
  8. }
  9.  
  10. // Further requests will work as expected until
  11. // you call setNextRequestWillFail(true) again

Creating your own connection adapters

You can create your own connection adapters and use them. You could, for example, create a connection adapter that uses persistent sockets, or a connection adapter with caching abilities, and use them as needed in your application.

In order to do so, you must create your own adapter class that implements the Zend_Http_Client_Adapter_Interface interface. The following example shows the skeleton of a user-implemented adapter class. All the public functions defined in this example must be defined in your adapter as well:

Example #9 Creating your own connection adapter

  1. span style="color: #808080; font-style: italic;">/**
  2.      * Set the configuration array for the adapter
  3.      *
  4.      * @param array $config
  5.      */// This rarely changes - you should usually copy the
  6.         // implementation in Zend_Http_Client_Adapter_Socket.
  7.     }
  8.  
  9.     /**
  10.      * Connect to the remote server
  11.      *
  12.      * @param string  $host
  13.      * @param int     $port
  14.      * @param boolean $secure
  15.      */// Set up the connection to the remote server
  16.     }
  17.  
  18.     /**
  19.      * Send request to the remote server
  20.      *
  21.      * @param string        $method
  22.      * @param Zend_Uri_Http $url
  23.      * @param string        $http_ver
  24.      * @param array         $headers
  25.      * @param string        $body
  26.      * @return string Request as text
  27.      */'1.1''')
  28.     {
  29.         // Send request to the remote server.
  30.         // This function is expected to return the full request
  31.         // (headers and body) as a string
  32.     }
  33.  
  34.     /**
  35.      * Read response from server
  36.      *
  37.      * @return string
  38.      */// Read response from remote server and return it as a string
  39.     }
  40.  
  41.     /**
  42.      * Close the connection to the server
  43.      *
  44.      */// Close the connection to the remote server - called last.
  45.     }
  46. }
  47.  
  48. // Then, you could use this adapter:
  49. 'adapter' => 'MyApp_Http_Client_Adapter_BananaProtocol'
  50. ));

Zend_Http_Client - Advanced Usage