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 HTTP/1.1 RFC, HTTP 301 and 302 responses should be
17 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 HTTP 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 HTML 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>
184 <programlisting language="php"><![CDATA[
185 // Uploading arbitrary data as a file
186 $text = 'this is some plain text';
187 $client->setFileUpload('some_text.txt', 'upload', $text, 'text/plain');
189 // Uploading an existing file
190 $client->setFileUpload('/tmp/Backup.tar.gz', 'bufile');
193 $client->request('POST');
197 In the first example, the $text variable is uploaded and will be
198 available as $_FILES['upload'] on the server side. In the second
199 example, the existing file /tmp/Backup.tar.gz is uploaded to the
200 server and will be available as $_FILES['bufile']. The content type
201 will be guesses automatically if possible - and if not, the content
202 type will be set to 'application/octet-stream'.
206 <title>Uploading files</title>
209 When uploading files, the <acronym>HTTP</acronym> request content-type is
210 automatically set to multipart/form-data. Keep in mind that
211 you must send a POST or PUT request in order to upload files.
212 Most servers will ignore the requests body on other request
218 <sect2 id="zend.http.client.raw_post_data">
219 <title>Sending Raw POST Data</title>
222 You can use a <classname>Zend_Http_Client</classname> to send raw POST data using the
223 setRawData() method. This method takes two parameters: the first
224 is the data to send in the request body. The second optional
225 parameter is the content-type of the data. While this parameter is
226 optional, you should usually set it before sending the request -
227 either using setRawData(), or with another method: setEncType().
229 <example id="zend.http.client.raw_post_data.example-1">
230 <title>Sending Raw POST Data</title>
232 <programlisting language="php"><![CDATA[
234 ' <title>Islands in the Stream</title>' .
235 ' <author>Ernest Hemingway</author>' .
236 ' <year>1970</year>' .
239 $client->setRawData($xml, 'text/xml')->request('POST');
241 // Another way to do the same thing:
242 $client->setRawData($xml)->setEncType('text/xml')->request('POST');
246 The data should be available on the server side through <acronym>PHP</acronym>'s
247 $HTTP_RAW_POST_DATA variable or through the php://input stream.
251 <title>Using raw POST data</title>
254 Setting raw POST data for a request will override any POST
255 parameters or file uploads. You should not try to use both on
256 the same request. Keep in mind that most servers will ignore
257 the request body unless you send a POST request.
262 <sect2 id="zend.http.client.http_authentication">
263 <title>HTTP Authentication</title>
266 Currently, <classname>Zend_Http_Client</classname> only supports basic HTTP
267 authentication. This feature is utilized using the <methodname>setAuth()</methodname>
268 method, or by specifying a username and a password in the URI. The
269 <methodname>setAuth()</methodname> method
270 takes 3 parameters: The user name, the password and an optional
271 authentication type parameter. As mentioned, currently only basic
272 authentication is supported (digest authentication support is
275 <example id="zend.http.client.http_authentication.example-1">
276 <title>Setting HTTP Authentication User and Password</title>
278 <programlisting language="php"><![CDATA[
279 // Using basic authentication
280 $client->setAuth('shahar', 'myPassword!', Zend_Http_Client::AUTH_BASIC);
282 // Since basic auth is default, you can just do this:
283 $client->setAuth('shahar', 'myPassword!');
285 // You can also specify username and password in the URI
286 $client->setUri('http://christer:secret@example.com');
292 <sect2 id="zend.http.client.multiple_requests">
293 <title>Sending Multiple Requests With the Same Client</title>
296 <classname>Zend_Http_Client</classname> was also designed specifically to handle several
297 consecutive requests with the same object. This is useful in cases
298 where a script requires data to be fetched from several places, or
299 when accessing a specific <acronym>HTTP</acronym> resource requires logging in and
300 obtaining a session cookie, for example.
304 When performing several requests to the same host, it is highly
305 recommended to enable the 'keepalive' configuration flag. This way,
306 if the server supports keep-alive connections, the connection to the
307 server will only be closed once all requests are done and the Client
308 object is destroyed. This prevents the overhead of opening and
309 closing <acronym>TCP</acronym> connections to the server.
313 When you perform several requests with the same client, but want
314 to make sure all the request-specific parameters are cleared, you
315 should use the resetParameters() method. This ensures that GET and
316 POST parameters, request body and request-specific headers are
317 reset and are not reused in the next request.
321 <title>Resetting parameters</title>
324 Note that non-request specific headers are not reset by default
325 when the <methodname>resetParameters()</methodname> method is used.
326 Only the 'Content-length' and 'Content-type' headers are reset. This
327 allows you to set-and-forget headers like 'Accept-language' and
332 To clean all headers and other data except for URI and method, use
333 <methodname>resetParameters(true)</methodname>.
338 Another feature designed specifically for consecutive requests is
339 the Cookie Jar object. Cookie Jars allow you to automatically save
340 cookies set by the server in the first request, and send them on
341 consecutive requests transparently. This allows, for example, going
342 through an authentication request before sending the actual data
347 If your application requires one authentication request per user,
348 and consecutive requests might be performed in more than one script
349 in your application, it might be a good idea to store the Cookie Jar
350 object in the user's session. This way, you will only need to
351 authenticate the user once every session.
354 <example id="zend.http.client.multiple_requests.example-1">
355 <title>Performing consecutive requests with one client</title>
357 <programlisting language="php"><![CDATA[
358 // First, instantiate the client
359 $client = new Zend_Http_Client('http://www.example.com/fetchdata.php', array(
363 // Do we have the cookies stored in our session?
364 if (isset($_SESSION['cookiejar']) &&
365 $_SESSION['cookiejar'] instanceof Zend_Http_CookieJar)) {
367 $client->setCookieJar($_SESSION['cookiejar']);
369 // If we don't, authenticate and store cookies
370 $client->setCookieJar();
371 $client->setUri('http://www.example.com/login.php');
372 $client->setParameterPost(array(
374 'pass' => 'somesecret'
376 $client->request(Zend_Http_Client::POST);
378 // Now, clear parameters and set the URI to the original one
379 // (note that the cookies that were set by the server are now
380 // stored in the jar)
381 $client->resetParameters();
382 $client->setUri('http://www.example.com/fetchdata.php');
385 $response = $client->request(Zend_Http_Client::GET);
387 // Store cookies in session, for next page
388 $_SESSION['cookiejar'] = $client->getCookieJar();
393 <sect2 id="zend.http.client.streaming">
394 <title>Data Streaming</title>
397 By default, <classname>Zend_Http_Client</classname> accepts and returns data as
398 <acronym>PHP</acronym> strings. However, in many cases there are big files to be sent or
399 received, thus keeping them in memory might be unnecessary or too expensive. For these
400 cases, <classname>Zend_Http_Client</classname> supports reading data from files (and in
401 general, <acronym>PHP</acronym> streams) and writing data to files (streams).
405 In order to use stream to pass data to <classname>Zend_Http_Client</classname>,
406 use <methodname>setRawData()</methodname> method with data argument being stream
407 resource (e.g., result of <methodname>fopen()</methodname>).
409 <example id="zend.http.client.streaming.example-1">
410 <title>Sending file to HTTP server with streaming</title>
412 <programlisting language="php"><![CDATA[
413 $fp = fopen("mybigfile.zip", "r");
414 $client->setRawData($fp, 'application/zip')->request('PUT');
420 Only PUT requests currently support sending streams to HTTP server.
424 In order to receive data from the server as stream, use
425 <methodname>setStream()</methodname>. Optional argument specifies the filename where the
426 data will be stored. If the argument is just <constant>TRUE</constant> (default),
427 temporary file will be used and will be deleted once response object is destroyed.
428 Setting argument to <constant>FALSE</constant> disables the streaming functionality.
432 When using streaming, <methodname>request()</methodname> method will return object of
433 class <classname>Zend_Http_Client_Response_Stream</classname>, which has two useful
434 methods: <methodname>getStreamName()</methodname> will return the name of the file where
435 the response is stored, and <methodname>getStream()</methodname> will return stream from
436 which the response could be read.
440 You can either write the response to pre-defined file, or use temporary file for storing
441 it and send it out or write it to another file using regular stream functions.
443 <example id="zend.http.client.streaming.example-2">
444 <title>Receiving file from HTTP server with streaming</title>
446 <programlisting language="php"><![CDATA[
447 $client->setStream(); // will use temp file
448 $response = $client->request('GET');
450 copy($response->getStreamName(), "my/downloads/file");
452 $fp = fopen("my/downloads/file2", "w");
453 stream_copy_to_stream($response->getStream(), $fp);
454 // Also can write to known file
455 $client->setStream("my/downloads/myfile)->request('GET');