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.
57 <command>new Zend_Http_Client_Adapter_Test</command>). 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 <property>ssltransport</property>, <property>sslcert</property> and
181 <property>sslpassphrase</property> are only relevant when connecting using
182 <acronym>HTTPS</acronym>.
186 While the default <acronym>SSL</acronym> settings should work for most
187 applications, you might need to change them if the server
188 you are connecting to requires special client setup. If so,
189 you should read the sections about <acronym>SSL</acronym> transport layers and
191 url="http://www.php.net/manual/en/transports.php#transports.inet">here</ulink>.
196 <example id="zend.http.client.adapters.socket.example-1">
197 <title>Changing the HTTPS transport layer</title>
199 <programlisting language="php"><![CDATA[
200 // Set the configuration parameters
202 'adapter' => 'Zend_Http_Client_Adapter_Socket',
203 'ssltransport' => 'tls'
206 // Instantiate a client object
207 $client = new Zend_Http_Client('https://www.example.com', $config);
209 // The following request will be sent over a TLS secure connection.
210 $response = $client->request();
215 The result of the example above will be similar to opening a <acronym>TCP</acronym>
216 connection using the following <acronym>PHP</acronym> command:
220 <methodname>fsockopen('tls://www.example.com', 443)</methodname>
223 <sect3 id="zend.http.client.adapters.socket.streamcontext">
224 <title>Customizing and accessing the Socket adapter stream context</title>
227 Starting from Zend Framework 1.9,
228 <classname>Zend_Http_Client_Adapter_Socket</classname> provides direct access to the
230 url="http://php.net/manual/en/stream.contexts.php">stream context</ulink> used
231 to connect to the remote server. This allows the user to pass specific options and
232 parameters to the <acronym>TCP</acronym> stream, and to the <acronym>SSL</acronym>
233 wrapper in case of <acronym>HTTPS</acronym> connections.
237 You can access the stream context using the following methods of
238 <classname>Zend_Http_Client_Adapter_Socket</classname>:
243 <firstterm><methodname>setStreamContext($context)</methodname></firstterm>
244 Sets the stream context to be used by the adapter. Can accept either
245 a stream context resource created using the <ulink
246 url="http://php.net/manual/en/function.stream-context-create.php"><methodname>stream_context_create()</methodname></ulink>
247 <acronym>PHP</acronym> function, or an array of stream context options,
248 in the same format provided to this function. Providing an array will
249 create a new stream context using these options, and set it.
255 <firstterm><methodname>getStreamContext()</methodname></firstterm>
256 Get the stream context of the adapter. If no stream context was set,
257 will create a default stream context and return it. You can then set
258 or get the value of different context options using regular
259 <acronym>PHP</acronym> stream context functions.
265 <example id="zend.http.client.adapters.socket.streamcontext.example-1">
266 <title>Setting stream context options for the Socket adapter</title>
268 <programlisting language="php"><![CDATA[
272 // Bind local socket side to a specific interface
273 'bindto' => '10.1.2.3:50505'
276 // Verify server side certificate,
277 // do not accept invalid or self-signed SSL certificates
278 'verify_peer' => true,
279 'allow_self_signed' => false,
281 // Capture the peer's certificate
282 'capture_peer_cert' => true
286 // Create an adapter object and attach it to the HTTP client
287 $adapter = new Zend_Http_Client_Adapter_Socket();
288 $client = new Zend_Http_Client();
289 $client->setAdapter($adapter);
291 // Method 1: pass the options array to setStreamContext()
292 $adapter->setStreamContext($options);
294 // Method 2: create a stream context and pass it to setStreamContext()
295 $context = stream_context_create($options);
296 $adapter->setStreamContext($context);
298 // Method 3: get the default stream context and set the options on it
299 $context = $adapter->getStreamContext();
300 stream_context_set_option($context, $options);
302 // Now, preform the request
303 $response = $client->request();
305 // If everything went well, you can now access the context again
306 $opts = stream_context_get_options($adapter->getStreamContext());
307 echo $opts['ssl']['peer_certificate'];
313 Note that you must set any stream context options before using the adapter
314 to preform actual requests. If no context is set before preforming
315 <acronym>HTTP</acronym> requests with the Socket adapter, a default stream
316 context will be created. This context resource could be accessed after
317 preforming any requests using the <methodname>getStreamContext()</methodname>
324 <sect2 id="zend.http.client.adapters.proxy">
325 <title>The Proxy Adapter</title>
328 The <classname>Zend_Http_Client_Adapter_Proxy</classname> adapter is similar to the
329 default Socket adapter - only the connection is made through an <acronym>HTTP</acronym>
330 proxy server instead of a direct connection to the target server. This
331 allows usage of <classname>Zend_Http_Client</classname> behind proxy servers - which is
332 sometimes needed for security or performance reasons.
336 Using the Proxy adapter requires several additional configuration
337 parameters to be set, in addition to the default 'adapter' option:
339 <table id="zend.http.client.adapters.proxy.table">
340 <title>Zend_Http_Client configuration parameters</title>
345 <entry>Parameter</entry>
346 <entry>Description</entry>
347 <entry>Expected Type</entry>
348 <entry>Example Value</entry>
354 <entry>proxy_host</entry>
355 <entry>Proxy server address</entry>
356 <entry>string</entry>
357 <entry>'proxy.myhost.com' or '10.1.2.3'</entry>
361 <entry>proxy_port</entry>
362 <entry>Proxy server <acronym>TCP</acronym> port</entry>
363 <entry>integer</entry>
364 <entry>8080 (default) or 81</entry>
368 <entry>proxy_user</entry>
369 <entry>Proxy user name, if required</entry>
370 <entry>string</entry>
371 <entry>'shahar' or '' for none (default)</entry>
375 <entry>proxy_pass</entry>
376 <entry>Proxy password, if required</entry>
377 <entry>string</entry>
378 <entry>'secret' or '' for none (default)</entry>
382 <entry>proxy_auth</entry>
383 <entry>Proxy <acronym>HTTP</acronym> authentication type</entry>
384 <entry>string</entry>
385 <entry>Zend_Http_Client::AUTH_BASIC (default)</entry>
393 proxy_host should always be set - if it is not set, the client will
394 fall back to a direct connection using
395 <classname>Zend_Http_Client_Adapter_Socket</classname>. proxy_port defaults to '8080' -
396 if your proxy listens on a different port you must set this one as well.
400 proxy_user and proxy_pass are only required if your proxy server
401 requires you to authenticate. Providing these will add a 'Proxy-Authentication'
402 header to the request. If your proxy does not require authentication,
403 you can leave these two options out.
407 proxy_auth sets the proxy authentication type, if your proxy server
408 requires authentication. Possibly values are similar to the ones
409 accepted by the Zend_Http_Client::setAuth() method. Currently, only
410 basic authentication (Zend_Http_Client::AUTH_BASIC) is supported.
413 <example id="zend.http.client.adapters.proxy.example-1">
414 <title>Using Zend_Http_Client behind a proxy server</title>
416 <programlisting language="php"><![CDATA[
417 // Set the configuration parameters
419 'adapter' => 'Zend_Http_Client_Adapter_Proxy',
420 'proxy_host' => 'proxy.int.zend.com',
421 'proxy_port' => 8000,
422 'proxy_user' => 'shahar.e',
423 'proxy_pass' => 'bananashaped'
426 // Instantiate a client object
427 $client = new Zend_Http_Client('http://www.example.com', $config);
429 // Continue working...
434 As mentioned, if proxy_host is not set or is set to a blank string,
435 the connection will fall back to a regular direct connection. This
436 allows you to easily write your application in a way that allows a
437 proxy to be used optionally, according to a configuration parameter.
442 Since the proxy adapter inherits from
443 <classname>Zend_Http_Client_Adapter_Socket</classname>, you can use the stream
444 context access method (see <xref
445 linkend="zend.http.client.adapters.socket.streamcontext" />) to set stream
446 context options on Proxy connections as demonstrated above.
451 <sect2 id="zend.http.client.adapters.curl">
452 <title>The cURL Adapter</title>
455 cURL is a standard <acronym>HTTP</acronym> client library that is distributed with many
456 operating systems and can be used in <acronym>PHP</acronym> via the cURL extension. It
457 offers functionality for many special cases which can occur for a
458 <acronym>HTTP</acronym> client and make it a perfect choice for a
459 <acronym>HTTP</acronym> adapter. It supports secure connections, proxy, all sorts of
460 authentication mechanisms and shines in applications that move large files around
464 <example id="zend.http.client.adapters.curl.example-1">
465 <title>Setting cURL options</title>
467 <programlisting language="php"><![CDATA[
469 'adapter' => 'Zend_Http_Client_Adapter_Curl',
470 'curloptions' => array(CURLOPT_FOLLOWLOCATION => true),
472 $client = new Zend_Http_Client($uri, $config);
477 By default the cURL adapter is configured to behave exactly like
478 the Socket Adapter and it also accepts the same configuration parameters
479 as the Socket and Proxy adapters. You can also change the cURL options by either
480 specifying the 'curloptions' key in the constructor of the adapter or by calling
481 <methodname>setCurlOption($name, $value)</methodname>. The <varname>$name</varname> key
482 corresponds to the CURL_* constants of the cURL extension. You can
483 get access to the Curl handle by calling <command>$adapter->getHandle();</command>
486 <example id="zend.http.client.adapters.curl.example-2">
487 <title>Transfering Files by Handle</title>
490 You can use cURL to transfer very large files over <acronym>HTTP</acronym> by
494 <programlisting language="php"><![CDATA[
495 $putFileSize = filesize("filepath");
496 $putFileHandle = fopen("filepath", "r");
498 $adapter = new Zend_Http_Client_Adapter_Curl();
499 $client = new Zend_Http_Client();
500 $client->setAdapter($adapter);
501 $adapter->setConfig(array(
502 'curloptions' => array(
503 CURLOPT_INFILE => $putFileHandle,
504 CURLOPT_INFILESIZE => $putFileSize
507 $client->request("PUT");
512 <sect2 id="zend.http.client.adapters.test">
513 <title>The Test Adapter</title>
516 Sometimes, it is very hard to test code that relies on <acronym>HTTP</acronym>
517 connections. For example, testing an application that pulls an <acronym>RSS</acronym>
518 feed from a remote server will require a network connection, which is not always
523 For this reason, the <classname>Zend_Http_Client_Adapter_Test</classname> adapter is
524 provided. You can write your application to use <classname>Zend_Http_Client</classname>,
525 and just for testing purposes, for example in your unit testing
526 suite, you can replace the default adapter with a Test adapter (a
527 mock object), allowing you to run tests without actually
528 performing server connections.
532 The <classname>Zend_Http_Client_Adapter_Test</classname> adapter provides an additional
533 method, setResponse() method. This method takes one parameter,
534 which represents an <acronym>HTTP</acronym> response as either text or a
535 <classname>Zend_Http_Response</classname> object. Once set, your Test adapter will
536 always return this response, without even performing an actual <acronym>HTTP</acronym>
540 <example id="zend.http.client.adapters.test.example-1">
541 <title>Testing Against a Single HTTP Response Stub</title>
543 <programlisting language="php"><![CDATA[
544 // Instantiate a new adapter and client
545 $adapter = new Zend_Http_Client_Adapter_Test();
546 $client = new Zend_Http_Client('http://www.example.com', array(
547 'adapter' => $adapter
550 // Set the expected response
551 $adapter->setResponse(
552 "HTTP/1.1 200 OK" . "\r\n" .
553 "Content-type: text/xml" . "\r\n" .
555 '<?xml version="1.0" encoding="UTF-8"?>' .
556 '<rss version="2.0" ' .
557 ' xmlns:content="http://purl.org/rss/1.0/modules/content/"' .
558 ' xmlns:wfw="http://wellformedweb.org/CommentAPI/"' .
559 ' xmlns:dc="http://purl.org/dc/elements/1.1/">' .
561 ' <title>Premature Optimization</title>' .
565 $response = $client->request('GET');
566 // .. continue parsing $response..
571 The above example shows how you can preset your <acronym>HTTP</acronym> client to
572 return the response you need. Then, you can continue testing your
573 own code, without being dependent on a network connection, the server's
574 response, etc. In this case, the test would continue to check how
575 the application parses the <acronym>XML</acronym> in the response body.
579 Sometimes, a single method call to an object can result in that
580 object performing multiple <acronym>HTTP</acronym> transactions. In this case, it's
581 not possible to use setResponse() alone because there's no
582 opportunity to set the next response(s) your program might need
583 before returning to the caller.
586 <example id="zend.http.client.adapters.test.example-2">
587 <title>Testing Against Multiple HTTP Response Stubs</title>
589 <programlisting language="php"><![CDATA[
590 // Instantiate a new adapter and client
591 $adapter = new Zend_Http_Client_Adapter_Test();
592 $client = new Zend_Http_Client('http://www.example.com', array(
593 'adapter' => $adapter
596 // Set the first expected response
597 $adapter->setResponse(
598 "HTTP/1.1 302 Found" . "\r\n" .
599 "Location: /" . "\r\n" .
600 "Content-Type: text/html" . "\r\n" .
603 ' <head><title>Moved</title></head>' .
604 ' <body><p>This page has moved.</p></body>' .
607 // Set the next successive response
608 $adapter->addResponse(
609 "HTTP/1.1 200 OK" . "\r\n" .
610 "Content-Type: text/html" . "\r\n" .
613 ' <head><title>My Pet Store Home Page</title></head>' .
614 ' <body><p>...</p></body>' .
617 // inject the http client object ($client) into your object
618 // being tested and then test your object's behavior below
623 The setResponse() method clears any responses in the
624 <classname>Zend_Http_Client_Adapter_Test</classname>'s buffer and sets the
625 first response that will be returned. The addResponse()
626 method will add successive responses.
630 The responses will be replayed in the order that they
631 were added. If more requests are made than the number
632 of responses stored, the responses will cycle again
637 In the example above, the adapter is configured to test your
638 object's behavior when it encounters a 302 redirect. Depending on
639 your application, following a redirect may or may not be desired
640 behavior. In our example, we expect that the redirect will be
641 followed and we configure the test adapter to help us test this.
642 The initial 302 response is set up with the setResponse() method
643 and the 200 response to be returned next is added with the
644 addResponse() method. After configuring the test adapter, inject
645 the <acronym>HTTP</acronym> client containing the adapter into your object under test
646 and test its behavior.
650 If you need the adapter to fail on demand you can use
651 <methodname>setNextRequestWillFail($flag)</methodname>. The method will cause the next
652 call to <methodname>connect()</methodname> to throw an
653 <classname>Zend_Http_Client_Adapter_Exception</classname> exception. This can be useful
654 when your application caches content from an external site (in case the site goes down)
655 and you want to test this feature.
658 <example id="zend.http.client.adapters.test.example-3">
659 <title>Forcing the adapter to fail</title>
661 <programlisting language="php"><![CDATA[
662 // Instantiate a new adapter and client
663 $adapter = new Zend_Http_Client_Adapter_Test();
664 $client = new Zend_Http_Client('http://www.example.com', array(
665 'adapter' => $adapter
668 // Force the next request to fail with an exception
669 $adapter->setNextRequestWillFail(true);
672 // This call will result in a Zend_Http_Client_Adapter_Exception
674 } catch (Zend_Http_Client_Adapter_Exception $e) {
678 // Further requests will work as expected until
679 // you call setNextRequestWillFail(true) again
684 <sect2 id="zend.http.client.adapters.extending">
685 <title>Creating your own connection adapters</title>
688 You can create your own connection adapters and use them. You could, for
689 example, create a connection adapter that uses persistent sockets,
690 or a connection adapter with caching abilities, and use them as
691 needed in your application.
695 In order to do so, you must create your own adapter class that implements
696 the <classname>Zend_Http_Client_Adapter_Interface</classname> interface. The following
697 example shows the skeleton of a user-implemented adapter class. All the public
698 functions defined in this example must be defined in your adapter as well:
701 <example id="zend.http.client.adapters.extending.example-1">
702 <title>Creating your own connection adapter</title>
704 <programlisting language="php"><![CDATA[
705 class MyApp_Http_Client_Adapter_BananaProtocol
706 implements Zend_Http_Client_Adapter_Interface
709 * Set the configuration array for the adapter
711 * @param array $config
713 public function setConfig($config = array())
715 // This rarely changes - you should usually copy the
716 // implementation in Zend_Http_Client_Adapter_Socket.
720 * Connect to the remote server
722 * @param string $host
724 * @param boolean $secure
726 public function connect($host, $port = 80, $secure = false)
728 // Set up the connection to the remote server
732 * Send request to the remote server
734 * @param string $method
735 * @param Zend_Uri_Http $url
736 * @param string $http_ver
737 * @param array $headers
738 * @param string $body
739 * @return string Request as text
741 public function write($method,
747 // Send request to the remote server.
748 // This function is expected to return the full request
749 // (headers and body) as a string
753 * Read response from server
757 public function read()
759 // Read response from remote server and return it as a string
763 * Close the connection to the server
766 public function close()
768 // Close the connection to the remote server - called last.
772 // Then, you could use this adapter:
773 $client = new Zend_Http_Client(array(
774 'adapter' => 'MyApp_Http_Client_Adapter_BananaProtocol'