1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect1 id="zend.http.client.advanced">
4 <title>Zend_Http_Client - Advanced Usage</title>
6 <sect2 id="zend.http.client.redirections">
7 <title>HTTP Redirections</title>
10 By default, <classname>Zend_Http_Client</classname> automatically handles
11 <acronym>HTTP</acronym> redirections, and will follow up to 5 redirections. This can be
12 changed by setting the 'maxredirects' configuration parameter.
16 According to the <acronym>HTTP</acronym>/1.1 RFC, <acronym>HTTP</acronym> 301 and 302
17 responses should be treated by the client by resending the same request to the
18 specified location - using the same request method. However, most
19 clients to not implement this and always use a GET request when
20 redirecting. By default, <classname>Zend_Http_Client</classname> does the same - when
21 redirecting on a 301 or 302 response, all GET and POST parameters
22 are reset, and a GET request is sent to the new location. This
23 behavior can be changed by setting the 'strictredirects' configuration
24 parameter to boolean <constant>TRUE</constant>:
25 <example id="zend.http.client.redirections.example-1">
26 <title>Forcing RFC 2616 Strict Redirections on 301 and 302 Responses</title>
28 <programlisting language="php"><![CDATA[
29 // Strict Redirections
30 $client->setConfig(array('strictredirects' => true));
32 // Non-strict Redirections
33 $client->setConfig(array('strictredirects' => false));
39 You can always get the number of redirections done after sending a
40 request using the getRedirectionsCount() method.
44 <sect2 id="zend.http.client.cookies">
45 <title>Adding Cookies and Using Cookie Persistence</title>
48 <classname>Zend_Http_Client</classname> provides an easy interface for adding cookies
49 to your request, so that no direct header modification is
50 required. This is done using the setCookie() method. This method
51 can be used in several ways:
53 <example id="zend.http.client.cookies.example-1">
54 <title>Setting Cookies Using setCookie()</title>
56 <programlisting language="php"><![CDATA[
57 // Easy and simple: by providing a cookie name and cookie value
58 $client->setCookie('flavor', 'chocolate chips');
60 // By directly providing a raw cookie string (name=value)
61 // Note that the value must be already URL encoded
62 $client->setCookie('flavor=chocolate%20chips');
64 // By providing a Zend_Http_Cookie object
65 $cookie = Zend_Http_Cookie::fromString('flavor=chocolate%20chips');
66 $client->setCookie($cookie);
70 For more information about <classname>Zend_Http_Cookie</classname> objects, see
71 <xref linkend="zend.http.cookies" />.
75 <classname>Zend_Http_Client</classname> also provides the means for cookie stickiness -
76 that is having the client internally store all sent and received
77 cookies, and resend them automatically on subsequent requests. This
78 is useful, for example when you need to log in to a remote site
79 first and receive and authentication or session ID cookie before
80 sending further requests.
82 <example id="zend.http.client.cookies.example-2">
83 <title>Enabling Cookie Stickiness</title>
85 <programlisting language="php"><![CDATA[
86 // To turn cookie stickiness on, set a Cookie Jar
87 $client->setCookieJar();
89 // First request: log in and start a session
90 $client->setUri('http://example.com/login.php');
91 $client->setParameterPost('user', 'h4x0r');
92 $client->setParameterPost('password', '1337');
93 $client->request('POST');
95 // The Cookie Jar automatically stores the cookies set
96 // in the response, like a session ID cookie.
98 // Now we can send our next request - the stored cookies
99 // will be automatically sent.
100 $client->setUri('http://example.com/read_member_news.php');
101 $client->request('GET');
105 For more information about the <classname>Zend_Http_CookieJar</classname> class, see
106 <xref linkend="zend.http.cookies.cookiejar" />.
110 <sect2 id="zend.http.client.custom_headers">
111 <title>Setting Custom Request Headers</title>
114 Setting custom headers can be done by using the setHeaders() method.
115 This method is quite diverse and can be used in several ways, as
116 the following example shows:
118 <example id="zend.http.client.custom_headers.example-1">
119 <title>Setting A Single Custom Request Header</title>
121 <programlisting language="php"><![CDATA[
122 // Setting a single header, overwriting any previous value
123 $client->setHeaders('Host', 'www.example.com');
125 // Another way of doing the exact same thing
126 $client->setHeaders('Host: www.example.com');
128 // Setting several values for the same header
129 // (useful mostly for Cookie headers):
130 $client->setHeaders('Cookie', array(
131 'PHPSESSID=1234567890abcdef1234567890abcdef',
139 setHeader() can also be easily used to set multiple headers in one
140 call, by providing an array of headers as a single parameter:
142 <example id="zend.http.client.custom_headers.example-2">
143 <title>Setting Multiple Custom Request Headers</title>
145 <programlisting language="php"><![CDATA[
146 // Setting multiple headers, overwriting any previous value
147 $client->setHeaders(array(
148 'Host' => 'www.example.com',
149 'Accept-encoding' => 'gzip,deflate',
150 'X-Powered-By' => 'Zend Framework'));
152 // The array can also contain full array strings:
153 $client->setHeaders(array(
154 'Host: www.example.com',
155 'Accept-encoding: gzip,deflate',
156 'X-Powered-By: Zend Framework'));
162 <sect2 id="zend.http.client.file_uploads">
163 <title>File Uploads</title>
166 You can upload files through <acronym>HTTP</acronym> using the setFileUpload method.
167 This method takes a file name as the first parameter, a form name
168 as the second parameter, and data as a third optional parameter.
169 If the third data parameter is <constant>NULL</constant>, the first file name parameter
170 is considered to be a real file on disk, and <classname>Zend_Http_Client</classname>
171 will try to read this file and upload it. If the data parameter is not
172 <constant>NULL</constant>, the first file name parameter will be sent as the file name,
173 but no actual file needs to exist on the disk.
174 The second form name parameter is always required, and is equivalent
175 to the "name" attribute of an >input< tag, if the file was to
176 be uploaded through an <acronym>HTML</acronym> form.
177 A fourth optional parameter provides the file's content-type. If
178 not specified, and <classname>Zend_Http_Client</classname> reads the file from the disk,
179 the mime_content_type function will be used to guess the file's
180 content type, if it is available. In any case, the default MIME
181 type will be application/octet-stream.
182 <example id="zend.http.client.file_uploads.example-1">
183 <title>Using setFileUpload to Upload Files</title>
185 <programlisting language="php"><![CDATA[
186 // Uploading arbitrary data as a file
187 $text = 'this is some plain text';
188 $client->setFileUpload('some_text.txt', 'upload', $text, 'text/plain');
190 // Uploading an existing file
191 $client->setFileUpload('/tmp/Backup.tar.gz', 'bufile');
194 $client->request('POST');
198 In the first example, the $text variable is uploaded and will be
199 available as $_FILES['upload'] on the server side. In the second
200 example, the existing file /tmp/Backup.tar.gz is uploaded to the
201 server and will be available as $_FILES['bufile']. The content type
202 will be guesses automatically if possible - and if not, the content
203 type will be set to 'application/octet-stream'.
207 <title>Uploading files</title>
210 When uploading files, the <acronym>HTTP</acronym> request content-type is
211 automatically set to multipart/form-data. Keep in mind that
212 you must send a POST or PUT request in order to upload files.
213 Most servers will ignore the requests body on other request
219 <sect2 id="zend.http.client.raw_post_data">
220 <title>Sending Raw POST Data</title>
223 You can use a <classname>Zend_Http_Client</classname> to send raw POST data using the
224 setRawData() method. This method takes two parameters: the first
225 is the data to send in the request body. The second optional
226 parameter is the content-type of the data. While this parameter is
227 optional, you should usually set it before sending the request -
228 either using setRawData(), or with another method: setEncType().
230 <example id="zend.http.client.raw_post_data.example-1">
231 <title>Sending Raw POST Data</title>
233 <programlisting language="php"><![CDATA[
235 ' <title>Islands in the Stream</title>' .
236 ' <author>Ernest Hemingway</author>' .
237 ' <year>1970</year>' .
240 $client->setRawData($xml, 'text/xml')->request('POST');
242 // Another way to do the same thing:
243 $client->setRawData($xml)->setEncType('text/xml')->request('POST');
247 The data should be available on the server side through <acronym>PHP</acronym>'s
248 $HTTP_RAW_POST_DATA variable or through the php://input stream.
252 <title>Using raw POST data</title>
255 Setting raw POST data for a request will override any POST
256 parameters or file uploads. You should not try to use both on
257 the same request. Keep in mind that most servers will ignore
258 the request body unless you send a POST request.
263 <sect2 id="zend.http.client.http_authentication">
264 <title>HTTP Authentication</title>
267 Currently, <classname>Zend_Http_Client</classname> only supports basic
268 <acronym>HTTP</acronym> authentication. This feature is utilized using the
269 <methodname>setAuth()</methodname> method, or by specifying a username and a password in
270 the URI. The <methodname>setAuth()</methodname> method
271 takes 3 parameters: The user name, the password and an optional
272 authentication type parameter. As mentioned, currently only basic
273 authentication is supported (digest authentication support is
276 <example id="zend.http.client.http_authentication.example-1">
277 <title>Setting HTTP Authentication User and Password</title>
279 <programlisting language="php"><![CDATA[
280 // Using basic authentication
281 $client->setAuth('shahar', 'myPassword!', Zend_Http_Client::AUTH_BASIC);
283 // Since basic auth is default, you can just do this:
284 $client->setAuth('shahar', 'myPassword!');
286 // You can also specify username and password in the URI
287 $client->setUri('http://christer:secret@example.com');
293 <sect2 id="zend.http.client.multiple_requests">
294 <title>Sending Multiple Requests With the Same Client</title>
297 <classname>Zend_Http_Client</classname> was also designed specifically to handle several
298 consecutive requests with the same object. This is useful in cases
299 where a script requires data to be fetched from several places, or
300 when accessing a specific <acronym>HTTP</acronym> resource requires logging in and
301 obtaining a session cookie, for example.
305 When performing several requests to the same host, it is highly
306 recommended to enable the 'keepalive' configuration flag. This way,
307 if the server supports keep-alive connections, the connection to the
308 server will only be closed once all requests are done and the Client
309 object is destroyed. This prevents the overhead of opening and
310 closing <acronym>TCP</acronym> connections to the server.
314 When you perform several requests with the same client, but want
315 to make sure all the request-specific parameters are cleared, you
316 should use the resetParameters() method. This ensures that GET and
317 POST parameters, request body and request-specific headers are
318 reset and are not reused in the next request.
322 <title>Resetting parameters</title>
325 Note that non-request specific headers are not reset by default
326 when the <methodname>resetParameters()</methodname> method is used.
327 Only the 'Content-length' and 'Content-type' headers are reset. This
328 allows you to set-and-forget headers like 'Accept-language' and
333 To clean all headers and other data except for URI and method, use
334 <methodname>resetParameters(true)</methodname>.
339 Another feature designed specifically for consecutive requests is
340 the Cookie Jar object. Cookie Jars allow you to automatically save
341 cookies set by the server in the first request, and send them on
342 consecutive requests transparently. This allows, for example, going
343 through an authentication request before sending the actual data
348 If your application requires one authentication request per user,
349 and consecutive requests might be performed in more than one script
350 in your application, it might be a good idea to store the Cookie Jar
351 object in the user's session. This way, you will only need to
352 authenticate the user once every session.
355 <example id="zend.http.client.multiple_requests.example-1">
356 <title>Performing consecutive requests with one client</title>
358 <programlisting language="php"><![CDATA[
359 // First, instantiate the client
360 $client = new Zend_Http_Client('http://www.example.com/fetchdata.php', array(
364 // Do we have the cookies stored in our session?
365 if (isset($_SESSION['cookiejar']) &&
366 $_SESSION['cookiejar'] instanceof Zend_Http_CookieJar)) {
368 $client->setCookieJar($_SESSION['cookiejar']);
370 // If we don't, authenticate and store cookies
371 $client->setCookieJar();
372 $client->setUri('http://www.example.com/login.php');
373 $client->setParameterPost(array(
375 'pass' => 'somesecret'
377 $client->request(Zend_Http_Client::POST);
379 // Now, clear parameters and set the URI to the original one
380 // (note that the cookies that were set by the server are now
381 // stored in the jar)
382 $client->resetParameters();
383 $client->setUri('http://www.example.com/fetchdata.php');
386 $response = $client->request(Zend_Http_Client::GET);
388 // Store cookies in session, for next page
389 $_SESSION['cookiejar'] = $client->getCookieJar();
394 <sect2 id="zend.http.client.streaming">
395 <title>Data Streaming</title>
398 By default, <classname>Zend_Http_Client</classname> accepts and returns data as
399 <acronym>PHP</acronym> strings. However, in many cases there are big files to be sent or
400 received, thus keeping them in memory might be unnecessary or too expensive. For these
401 cases, <classname>Zend_Http_Client</classname> supports reading data from files (and in
402 general, <acronym>PHP</acronym> streams) and writing data to files (streams).
406 In order to use stream to pass data to <classname>Zend_Http_Client</classname>,
407 use <methodname>setRawData()</methodname> method with data argument being stream
408 resource (e.g., result of <methodname>fopen()</methodname>).
410 <example id="zend.http.client.streaming.example-1">
411 <title>Sending file to HTTP server with streaming</title>
413 <programlisting language="php"><![CDATA[
414 $fp = fopen("mybigfile.zip", "r");
415 $client->setRawData($fp, 'application/zip')->request('PUT');
421 Only PUT requests currently support sending streams to <acronym>HTTP</acronym> server.
425 In order to receive data from the server as stream, use
426 <methodname>setStream()</methodname>. Optional argument specifies the filename where the
427 data will be stored. If the argument is just <constant>TRUE</constant> (default),
428 temporary file will be used and will be deleted once response object is destroyed.
429 Setting argument to <constant>FALSE</constant> disables the streaming functionality.
433 When using streaming, <methodname>request()</methodname> method will return object of
434 class <classname>Zend_Http_Client_Response_Stream</classname>, which has two useful
435 methods: <methodname>getStreamName()</methodname> will return the name of the file where
436 the response is stored, and <methodname>getStream()</methodname> will return stream from
437 which the response could be read.
441 You can either write the response to pre-defined file, or use temporary file for storing
442 it and send it out or write it to another file using regular stream functions.
444 <example id="zend.http.client.streaming.example-2">
445 <title>Receiving file from HTTP server with streaming</title>
447 <programlisting language="php"><![CDATA[
448 $client->setStream(); // will use temp file
449 $response = $client->request('GET');
451 copy($response->getStreamName(), "my/downloads/file");
453 $fp = fopen("my/downloads/file2", "w");
454 stream_copy_to_stream($response->getStream(), $fp);
455 // Also can write to known file
456 $client->setStream("my/downloads/myfile)->request('GET');