1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.http.client.adapters">
4 <title>Zend_Http_Client - Connection Adapters</title>
6 <sect2 id="zend.http.client.adapters.overview">
7 <title>Overview</title>
10 <classname>Zend_Http_Client</classname> is based on a connection adapter design. The
11 connection adapter is the object in charge of performing the
12 actual connection to the server, as well as writing requests
13 and reading responses.
14 This connection adapter can be replaced, and you can create and
15 extend the default connection adapters to suite your special needs,
16 without the need to extend or replace the entire <acronym>HTTP</acronym> client
17 class, and with the same interface.
21 Currently, the <classname>Zend_Http_Client</classname> class provides four built-in
27 <classname>Zend_Http_Client_Adapter_Socket</classname> (default)
33 <classname>Zend_Http_Client_Adapter_Proxy</classname>
39 <classname>Zend_Http_Client_Adapter_Curl</classname>
45 <classname>Zend_Http_Client_Adapter_Test</classname>
52 The <classname>Zend_Http_Client</classname> object's adapter connection adapter is set
53 using the 'adapter' configuration option. When instantiating the
54 client object, you can set the 'adapter' configuration option to
55 a string containing the adapter's name (eg. 'Zend_Http_Client_Adapter_Socket')
56 or to a variable holding an adapter object (eg. <code>
57 new Zend_Http_Client_Adapter_Test</code>). You can also set the
58 adapter later, using the <classname>Zend_Http_Client->setConfig()</classname> method.
62 <sect2 id="zend.http.client.adapters.socket">
63 <title>The Socket Adapter</title>
66 The default connection adapter is the
67 <classname>Zend_Http_Client_Adapter_Socket</classname> adapter - this adapter will be
68 used unless you explicitly set the connection adapter. The Socket adapter is based on
69 <acronym>PHP</acronym>'s built-in fsockopen() function, and does not require any special
70 extensions or compilation flags.
74 The Socket adapter allows several extra configuration options that
75 can be set using <classname>Zend_Http_Client->setConfig()</classname> or
76 passed to the client constructor.
78 <table id="zend.http.client.adapter.socket.configuration.table">
79 <title>Zend_Http_Client_Adapter_Socket configuration parameters</title>
84 <entry>Parameter</entry>
85 <entry>Description</entry>
86 <entry>Expected Type</entry>
87 <entry>Default Value</entry>
93 <entry>persistent</entry>
96 Whether to use persistent <acronym>TCP</acronym> connections
99 <entry>boolean</entry>
100 <entry><constant>FALSE</constant></entry>
104 <entry>ssltransport</entry>
105 <entry>SSL transport layer (eg. 'sslv2', 'tls')</entry>
106 <entry>string</entry>
111 <entry>sslcert</entry>
114 Path to a <acronym>PEM</acronym> encoded <acronym>SSL</acronym>
118 <entry>string</entry>
119 <entry><constant>NULL</constant></entry>
123 <entry>sslpassphrase</entry>
126 Passphrase for the <acronym>SSL</acronym> certificate file
129 <entry>string</entry>
130 <entry><constant>NULL</constant></entry>
134 <entry>sslusecontext</entry>
137 Enables proxied connections to use SSL even if
138 the proxy connection itself does not.
141 <entry>boolean</entry>
142 <entry><constant>FALSE</constant></entry>
149 <title>Persistent TCP Connections</title>
152 Using persistent <acronym>TCP</acronym> connections can potentially speed up
153 <acronym>HTTP</acronym> requests - but in most use cases, will have little
154 positive effect and might overload the <acronym>HTTP</acronym> server you are
159 It is recommended to use persistent <acronym>TCP</acronym> connections only if
160 you connect to the same server very frequently, and are
161 sure that the server is capable of handling a large number
162 of concurrent connections. In any case you are encouraged
163 to benchmark the effect of persistent connections on both
164 the client speed and server load before using this option.
168 Additionally, when using persistent connections it is
169 recommended to enable Keep-Alive <acronym>HTTP</acronym> requests as described
170 in <xref linkend="zend.http.client.configuration" /> -
171 otherwise persistent connections might have little or no
177 <title>HTTPS SSL Stream Parameters</title>
180 <code>ssltransport, sslcert</code> and <code>sslpassphrase</code>
181 are only relevant when connecting using <acronym>HTTPS</acronym>.
185 While the default <acronym>SSL</acronym> settings should work for most
186 applications, you might need to change them if the server
187 you are connecting to requires special client setup. If so,
188 you should read the sections about <acronym>SSL</acronym> transport layers and
190 url="http://www.php.net/manual/en/transports.php#transports.inet">here</ulink>.
195 <example id="zend.http.client.adapters.socket.example-1">
196 <title>Changing the HTTPS transport layer</title>
198 <programlisting language="php"><![CDATA[
199 // Set the configuration parameters
201 'adapter' => 'Zend_Http_Client_Adapter_Socket',
202 'ssltransport' => 'tls'
205 // Instantiate a client object
206 $client = new Zend_Http_Client('https://www.example.com', $config);
208 // The following request will be sent over a TLS secure connection.
209 $response = $client->request();
214 The result of the example above will be similar to opening a <acronym>TCP</acronym>
215 connection using the following <acronym>PHP</acronym> command:
219 <methodname>fsockopen('tls://www.example.com', 443)</methodname>
222 <sect3 id="zend.http.client.adapters.socket.streamcontext">
223 <title>Customizing and accessing the Socket adapter stream context</title>
226 Starting from Zend Framework 1.9,
227 <classname>Zend_Http_Client_Adapter_Socket</classname> provides direct access to the
229 url="http://php.net/manual/en/stream.contexts.php">stream context</ulink> used
230 to connect to the remote server. This allows the user to pass specific options and
231 parameters to the <acronym>TCP</acronym> stream, and to the <acronym>SSL</acronym>
232 wrapper in case of <acronym>HTTPS</acronym> connections.
236 You can access the stream context using the following methods of
237 <classname>Zend_Http_Client_Adapter_Socket</classname>:
242 <firstterm><methodname>setStreamContext($context)</methodname></firstterm>
243 Sets the stream context to be used by the adapter. Can accept either
244 a stream context resource created using the <ulink
245 url="http://php.net/manual/en/function.stream-context-create.php"><methodname>stream_context_create()</methodname></ulink>
246 <acronym>PHP</acronym> function, or an array of stream context options,
247 in the same format provided to this function. Providing an array will
248 create a new stream context using these options, and set it.
254 <firstterm><methodname>getStreamContext()</methodname></firstterm>
255 Get the stream context of the adapter. If no stream context was set,
256 will create a default stream context and return it. You can then set
257 or get the value of different context options using regular
258 <acronym>PHP</acronym> stream context functions.
264 <example id="zend.http.client.adapters.socket.streamcontext.example-1">
265 <title>Setting stream context options for the Socket adapter</title>
267 <programlisting language="php"><![CDATA[
271 // Bind local socket side to a specific interface
272 'bindto' => '10.1.2.3:50505'
275 // Verify server side certificate,
276 // do not accept invalid or self-signed SSL certificates
277 'verify_peer' => true,
278 'allow_self_signed' => false,
280 // Capture the peer's certificate
281 'capture_peer_cert' => true
285 // Create an adapter object and attach it to the HTTP client
286 $adapter = new Zend_Http_Client_Adapter_Socket();
287 $client = new Zend_Http_Client();
288 $client->setAdapter($adapter);
290 // Method 1: pass the options array to setStreamContext()
291 $adapter->setStreamContext($options);
293 // Method 2: create a stream context and pass it to setStreamContext()
294 $context = stream_context_create($options);
295 $adapter->setStreamContext($context);
297 // Method 3: get the default stream context and set the options on it
298 $context = $adapter->getStreamContext();
299 stream_context_set_option($context, $options);
301 // Now, preform the request
302 $response = $client->request();
304 // If everything went well, you can now access the context again
305 $opts = stream_context_get_options($adapter->getStreamContext());
306 echo $opts['ssl']['peer_certificate'];
312 Note that you must set any stream context options before using the adapter
313 to preform actual requests. If no context is set before preforming
314 <acronym>HTTP</acronym> requests with the Socket adapter, a default stream
315 context will be created. This context resource could be accessed after
316 preforming any requests using the <methodname>getStreamContext()</methodname>
323 <sect2 id="zend.http.client.adapters.proxy">
324 <title>The Proxy Adapter</title>
327 The <classname>Zend_Http_Client_Adapter_Proxy</classname> adapter is similar to the
328 default Socket adapter - only the connection is made through an <acronym>HTTP</acronym>
329 proxy server instead of a direct connection to the target server. This
330 allows usage of <classname>Zend_Http_Client</classname> behind proxy servers - which is
331 sometimes needed for security or performance reasons.
335 Using the Proxy adapter requires several additional configuration
336 parameters to be set, in addition to the default 'adapter' option:
338 <table id="zend.http.client.adapters.proxy.table">
339 <title>Zend_Http_Client configuration parameters</title>
344 <entry>Parameter</entry>
345 <entry>Description</entry>
346 <entry>Expected Type</entry>
347 <entry>Example Value</entry>
353 <entry>proxy_host</entry>
354 <entry>Proxy server address</entry>
355 <entry>string</entry>
356 <entry>'proxy.myhost.com' or '10.1.2.3'</entry>
360 <entry>proxy_port</entry>
361 <entry>Proxy server <acronym>TCP</acronym> port</entry>
362 <entry>integer</entry>
363 <entry>8080 (default) or 81</entry>
367 <entry>proxy_user</entry>
368 <entry>Proxy user name, if required</entry>
369 <entry>string</entry>
370 <entry>'shahar' or '' for none (default)</entry>
374 <entry>proxy_pass</entry>
375 <entry>Proxy password, if required</entry>
376 <entry>string</entry>
377 <entry>'secret' or '' for none (default)</entry>
381 <entry>proxy_auth</entry>
382 <entry>Proxy <acronym>HTTP</acronym> authentication type</entry>
383 <entry>string</entry>
384 <entry>Zend_Http_Client::AUTH_BASIC (default)</entry>
392 proxy_host should always be set - if it is not set, the client will
393 fall back to a direct connection using
394 <classname>Zend_Http_Client_Adapter_Socket</classname>. proxy_port defaults to '8080' -
395 if your proxy listens on a different port you must set this one as well.
399 proxy_user and proxy_pass are only required if your proxy server
400 requires you to authenticate. Providing these will add a 'Proxy-Authentication'
401 header to the request. If your proxy does not require authentication,
402 you can leave these two options out.
406 proxy_auth sets the proxy authentication type, if your proxy server
407 requires authentication. Possibly values are similar to the ones
408 accepted by the Zend_Http_Client::setAuth() method. Currently, only
409 basic authentication (Zend_Http_Client::AUTH_BASIC) is supported.
412 <example id="zend.http.client.adapters.proxy.example-1">
413 <title>Using Zend_Http_Client behind a proxy server</title>
415 <programlisting language="php"><![CDATA[
416 // Set the configuration parameters
418 'adapter' => 'Zend_Http_Client_Adapter_Proxy',
419 'proxy_host' => 'proxy.int.zend.com',
420 'proxy_port' => 8000,
421 'proxy_user' => 'shahar.e',
422 'proxy_pass' => 'bananashaped'
425 // Instantiate a client object
426 $client = new Zend_Http_Client('http://www.example.com', $config);
428 // Continue working...
433 As mentioned, if proxy_host is not set or is set to a blank string,
434 the connection will fall back to a regular direct connection. This
435 allows you to easily write your application in a way that allows a
436 proxy to be used optionally, according to a configuration parameter.
441 Since the proxy adapter inherits from
442 <classname>Zend_Http_Client_Adapter_Socket</classname>, you can use the stream
443 context access method (see <xref
444 linkend="zend.http.client.adapters.socket.streamcontext" />) to set stream
445 context options on Proxy connections as demonstrated above.
450 <sect2 id="zend.http.client.adapters.curl">
451 <title>The cURL Adapter</title>
454 cURL is a standard <acronym>HTTP</acronym> client library that is distributed with many
455 operating systems and can be used in <acronym>PHP</acronym> via the cURL extension. It
456 offers functionality for many special cases which can occur for a
457 <acronym>HTTP</acronym> client and make it a perfect choice for a
458 <acronym>HTTP</acronym> adapter. It supports secure connections, proxy, all sorts of
459 authentication mechanisms and shines in applications that move large files around
463 <example id="zend.http.client.adapters.curl.example-1">
464 <title>Setting cURL options</title>
466 <programlisting language="php"><![CDATA[
468 'adapter' => 'Zend_Http_Client_Adapter_Curl',
469 'curloptions' => array(CURLOPT_FOLLOWLOCATION => true),
471 $client = new Zend_Http_Client($uri, $config);
476 By default the cURL adapter is configured to behave exactly like
477 the Socket Adapter and it also accepts the same configuration parameters
478 as the Socket and Proxy adapters. You can also change the cURL options by either
479 specifying the 'curloptions' key in the constructor of the adapter or by calling
480 <methodname>setCurlOption($name, $value)</methodname>. The <varname>$name</varname> key
481 corresponds to the CURL_* constants of the cURL extension. You can
482 get access to the Curl handle by calling <code>$adapter->getHandle();</code>
485 <example id="zend.http.client.adapters.curl.example-2">
486 <title>Transfering Files by Handle</title>
489 You can use cURL to transfer very large files over <acronym>HTTP</acronym> by
493 <programlisting language="php"><![CDATA[
494 $putFileSize = filesize("filepath");
495 $putFileHandle = fopen("filepath", "r");
497 $adapter = new Zend_Http_Client_Adapter_Curl();
498 $client = new Zend_Http_Client();
499 $client->setAdapter($adapter);
500 $adapter->setConfig(array(
501 'curloptions' => array(
502 CURLOPT_INFILE => $putFileHandle,
503 CURLOPT_INFILESIZE => $putFileSize
506 $client->request("PUT");
511 <sect2 id="zend.http.client.adapters.test">
512 <title>The Test Adapter</title>
515 Sometimes, it is very hard to test code that relies on <acronym>HTTP</acronym>
516 connections. For example, testing an application that pulls an <acronym>RSS</acronym>
517 feed from a remote server will require a network connection, which is not always
522 For this reason, the <classname>Zend_Http_Client_Adapter_Test</classname> adapter is
523 provided. You can write your application to use <classname>Zend_Http_Client</classname>,
524 and just for testing purposes, for example in your unit testing
525 suite, you can replace the default adapter with a Test adapter (a
526 mock object), allowing you to run tests without actually
527 performing server connections.
531 The <classname>Zend_Http_Client_Adapter_Test</classname> adapter provides an additional
532 method, setResponse() method. This method takes one parameter,
533 which represents an <acronym>HTTP</acronym> response as either text or a
534 <classname>Zend_Http_Response</classname> object. Once set, your Test adapter will
535 always return this response, without even performing an actual <acronym>HTTP</acronym>
539 <example id="zend.http.client.adapters.test.example-1">
540 <title>Testing Against a Single HTTP Response Stub</title>
542 <programlisting language="php"><![CDATA[
543 // Instantiate a new adapter and client
544 $adapter = new Zend_Http_Client_Adapter_Test();
545 $client = new Zend_Http_Client('http://www.example.com', array(
546 'adapter' => $adapter
549 // Set the expected response
550 $adapter->setResponse(
551 "HTTP/1.1 200 OK" . "\r\n" .
552 "Content-type: text/xml" . "\r\n" .
554 '<?xml version="1.0" encoding="UTF-8"?>' .
555 '<rss version="2.0" ' .
556 ' xmlns:content="http://purl.org/rss/1.0/modules/content/"' .
557 ' xmlns:wfw="http://wellformedweb.org/CommentAPI/"' .
558 ' xmlns:dc="http://purl.org/dc/elements/1.1/">' .
560 ' <title>Premature Optimization</title>' .
564 $response = $client->request('GET');
565 // .. continue parsing $response..
570 The above example shows how you can preset your <acronym>HTTP</acronym> client to
571 return the response you need. Then, you can continue testing your
572 own code, without being dependent on a network connection, the server's
573 response, etc. In this case, the test would continue to check how
574 the application parses the <acronym>XML</acronym> in the response body.
578 Sometimes, a single method call to an object can result in that
579 object performing multiple <acronym>HTTP</acronym> transactions. In this case, it's
580 not possible to use setResponse() alone because there's no
581 opportunity to set the next response(s) your program might need
582 before returning to the caller.
585 <example id="zend.http.client.adapters.test.example-2">
586 <title>Testing Against Multiple HTTP Response Stubs</title>
588 <programlisting language="php"><![CDATA[
589 // Instantiate a new adapter and client
590 $adapter = new Zend_Http_Client_Adapter_Test();
591 $client = new Zend_Http_Client('http://www.example.com', array(
592 'adapter' => $adapter
595 // Set the first expected response
596 $adapter->setResponse(
597 "HTTP/1.1 302 Found" . "\r\n" .
598 "Location: /" . "\r\n" .
599 "Content-Type: text/html" . "\r\n" .
602 ' <head><title>Moved</title></head>' .
603 ' <body><p>This page has moved.</p></body>' .
606 // Set the next successive response
607 $adapter->addResponse(
608 "HTTP/1.1 200 OK" . "\r\n" .
609 "Content-Type: text/html" . "\r\n" .
612 ' <head><title>My Pet Store Home Page</title></head>' .
613 ' <body><p>...</p></body>' .
616 // inject the http client object ($client) into your object
617 // being tested and then test your object's behavior below
622 The setResponse() method clears any responses in the
623 <classname>Zend_Http_Client_Adapter_Test</classname>'s buffer and sets the
624 first response that will be returned. The addResponse()
625 method will add successive responses.
629 The responses will be replayed in the order that they
630 were added. If more requests are made than the number
631 of responses stored, the responses will cycle again
636 In the example above, the adapter is configured to test your
637 object's behavior when it encounters a 302 redirect. Depending on
638 your application, following a redirect may or may not be desired
639 behavior. In our example, we expect that the redirect will be
640 followed and we configure the test adapter to help us test this.
641 The initial 302 response is set up with the setResponse() method
642 and the 200 response to be returned next is added with the
643 addResponse() method. After configuring the test adapter, inject
644 the <acronym>HTTP</acronym> client containing the adapter into your object under test
645 and test its behavior.
649 If you need the adapter to fail on demand you can use
650 <methodname>setNextRequestWillFail($flag)</methodname>. The method will cause the next
651 call to <methodname>connect()</methodname> to throw an
652 <classname>Zend_Http_Client_Adapter_Exception</classname> exception. This can be useful
653 when your application caches content from an external site (in case the site goes down)
654 and you want to test this feature.
657 <example id="zend.http.client.adapters.test.example-3">
658 <title>Forcing the adapter to fail</title>
660 <programlisting language="php"><![CDATA[
661 // Instantiate a new adapter and client
662 $adapter = new Zend_Http_Client_Adapter_Test();
663 $client = new Zend_Http_Client('http://www.example.com', array(
664 'adapter' => $adapter
667 // Force the next request to fail with an exception
668 $adapter->setNextRequestWillFail(true);
671 // This call will result in a Zend_Http_Client_Adapter_Exception
673 } catch (Zend_Http_Client_Adapter_Exception $e) {
677 // Further requests will work as expected until
678 // you call setNextRequestWillFail(true) again
683 <sect2 id="zend.http.client.adapters.extending">
684 <title>Creating your own connection adapters</title>
687 You can create your own connection adapters and use them. You could, for
688 example, create a connection adapter that uses persistent sockets,
689 or a connection adapter with caching abilities, and use them as
690 needed in your application.
694 In order to do so, you must create your own adapter class that implements
695 the <classname>Zend_Http_Client_Adapter_Interface</classname> interface. The following
696 example shows the skeleton of a user-implemented adapter class. All the public
697 functions defined in this example must be defined in your adapter as well:
700 <example id="zend.http.client.adapters.extending.example-1">
701 <title>Creating your own connection adapter</title>
703 <programlisting language="php"><![CDATA[
704 class MyApp_Http_Client_Adapter_BananaProtocol
705 implements Zend_Http_Client_Adapter_Interface
708 * Set the configuration array for the adapter
710 * @param array $config
712 public function setConfig($config = array())
714 // This rarely changes - you should usually copy the
715 // implementation in Zend_Http_Client_Adapter_Socket.
719 * Connect to the remote server
721 * @param string $host
723 * @param boolean $secure
725 public function connect($host, $port = 80, $secure = false)
727 // Set up the connection to the remote server
731 * Send request to the remote server
733 * @param string $method
734 * @param Zend_Uri_Http $url
735 * @param string $http_ver
736 * @param array $headers
737 * @param string $body
738 * @return string Request as text
740 public function write($method,
746 // Send request to the remote server.
747 // This function is expected to return the full request
748 // (headers and body) as a string
752 * Read response from server
756 public function read()
758 // Read response from remote server and return it as a string
762 * Close the connection to the server
765 public function close()
767 // Close the connection to the remote server - called last.
771 // Then, you could use this adapter:
772 $client = new Zend_Http_Client(array(
773 'adapter' => 'MyApp_Http_Client_Adapter_BananaProtocol'