Zend_Http_Client - Advanced Usage - Zend_Http

Zend_Http_Client - Advanced Usage

HTTP Redirections

By default, Zend_Http_Client automatically handles HTTP redirections, and will follow up to 5 redirections. This can be changed by setting the 'maxredirects' configuration parameter.

According to the HTTP/1.1 RFC, HTTP 301 and 302 responses should be treated by the client by resending the same request to the specified location - using the same request method. However, most clients to not implement this and always use a GET request when redirecting. By default, Zend_Http_Client does the same - when redirecting on a 301 or 302 response, all GET and POST parameters are reset, and a GET request is sent to the new location. This behavior can be changed by setting the 'strictredirects' configuration parameter to boolean TRUE:

Example #1 Forcing RFC 2616 Strict Redirections on 301 and 302 Responses

  1. // Strict Redirections
  2. $client->setConfig(array('strictredirects' => true));
  4. // Non-strict Redirections
  5. $client->setConfig(array('strictredirects' => false));

You can always get the number of redirections done after sending a request using the getRedirectionsCount() method.

Adding Cookies and Using Cookie Persistence

Zend_Http_Client provides an easy interface for adding cookies to your request, so that no direct header modification is required. This is done using the setCookie() method. This method can be used in several ways:

Example #2 Setting Cookies Using setCookie()

  1. // Easy and simple: by providing a cookie name and cookie value
  2. $client->setCookie('flavor', 'chocolate chips');
  4. // By directly providing a raw cookie string (name=value)
  5. // Note that the value must be already URL encoded
  6. $client->setCookie('flavor=chocolate%20chips');
  8. // By providing a Zend_Http_Cookie object
  9. $cookie = Zend_Http_Cookie::fromString('flavor=chocolate%20chips');
  10. $client->setCookie($cookie);
For more information about Zend_Http_Cookie objects, see this section.

Zend_Http_Client also provides the means for cookie stickiness - that is having the client internally store all sent and received cookies, and resend them automatically on subsequent requests. This is useful, for example when you need to log in to a remote site first and receive and authentication or session ID cookie before sending further requests.

Example #3 Enabling Cookie Stickiness

  1. // To turn cookie stickiness on, set a Cookie Jar
  2. $client->setCookieJar();
  4. // First request: log in and start a session
  5. $client->setUri('');
  6. $client->setParameterPost('user', 'h4x0r');
  7. $client->setParameterPost('password', '1337');
  8. $client->request('POST');
  10. // The Cookie Jar automatically stores the cookies set
  11. // in the response, like a session ID cookie.
  13. // Now we can send our next request - the stored cookies
  14. // will be automatically sent.
  15. $client->setUri('');
  16. $client->request('GET');
For more information about the Zend_Http_CookieJar class, see this section.

Setting Custom Request Headers

Setting custom headers can be done by using the setHeaders() method. This method is quite diverse and can be used in several ways, as the following example shows:

Example #4 Setting A Single Custom Request Header

  1. // Setting a single header, overwriting any previous value
  2. $client->setHeaders('Host', '');
  4. // Another way of doing the exact same thing
  5. $client->setHeaders('Host:');
  7. // Setting several values for the same header
  8. // (useful mostly for Cookie headers):
  9. $client->setHeaders('Cookie', array(
  10.     'PHPSESSID=1234567890abcdef1234567890abcdef',
  11.     'language=he'
  12. ));

setHeader() can also be easily used to set multiple headers in one call, by providing an array of headers as a single parameter:

Example #5 Setting Multiple Custom Request Headers

  1. // Setting multiple headers, overwriting any previous value
  2. $client->setHeaders(array(
  3.     'Host' => '',
  4.     'Accept-encoding' => 'gzip,deflate',
  5.     'X-Powered-By' => 'Zend Framework'));
  7. // The array can also contain full array strings:
  8. $client->setHeaders(array(
  9.     'Host:',
  10.     'Accept-encoding: gzip,deflate',
  11.     'X-Powered-By: Zend Framework'));

File Uploads

You can upload files through HTTP using the setFileUpload method. This method takes a file name as the first parameter, a form name as the second parameter, and data as a third optional parameter. If the third data parameter is NULL, the first file name parameter is considered to be a real file on disk, and Zend_Http_Client will try to read this file and upload it. If the data parameter is not NULL, the first file name parameter will be sent as the file name, but no actual file needs to exist on the disk. The second form name parameter is always required, and is equivalent to the "name" attribute of an >input< tag, if the file was to be uploaded through an HTML form. A fourth optional parameter provides the file's content-type. If not specified, and Zend_Http_Client reads the file from the disk, the mime_content_type function will be used to guess the file's content type, if it is available. In any case, the default MIME type will be application/octet-stream.

Example #6 Using setFileUpload to Upload Files

  1. // Uploading arbitrary data as a file
  2. $text = 'this is some plain text';
  3. $client->setFileUpload('some_text.txt', 'upload', $text, 'text/plain');
  5. // Uploading an existing file
  6. $client->setFileUpload('/tmp/Backup.tar.gz', 'bufile');
  8. // Send the files
  9. $client->request('POST');
In the first example, the $text variable is uploaded and will be available as $_FILES['upload'] on the server side. In the second example, the existing file /tmp/Backup.tar.gz is uploaded to the server and will be available as $_FILES['bufile']. The content type will be guesses automatically if possible - and if not, the content type will be set to 'application/octet-stream'.

Note: Uploading files
When uploading files, the HTTP request content-type is automatically set to multipart/form-data. Keep in mind that you must send a POST or PUT request in order to upload files. Most servers will ignore the requests body on other request methods.

Sending Raw POST Data

You can use a Zend_Http_Client to send raw POST data using the setRawData() method. This method takes two parameters: the first is the data to send in the request body. The second optional parameter is the content-type of the data. While this parameter is optional, you should usually set it before sending the request - either using setRawData(), or with another method: setEncType().

Example #7 Sending Raw POST Data

  1. $xml = '<book>' .
  2.        '  <title>Islands in the Stream</title>' .
  3.        '  <author>Ernest Hemingway</author>' .
  4.        '  <year>1970</year>' .
  5.        '</book>';
  7. $client->setRawData($xml, 'text/xml')->request('POST');
  9. // Another way to do the same thing:
  10. $client->setRawData($xml)->setEncType('text/xml')->request('POST');
The data should be available on the server side through PHP's $HTTP_RAW_POST_DATA variable or through the php://input stream.

Note: Using raw POST data
Setting raw POST data for a request will override any POST parameters or file uploads. You should not try to use both on the same request. Keep in mind that most servers will ignore the request body unless you send a POST request.

HTTP Authentication

Currently, Zend_Http_Client only supports basic HTTP authentication. This feature is utilized using the setAuth() method, or by specifying a username and a password in the URI. The setAuth() method takes 3 parameters: The user name, the password and an optional authentication type parameter. As mentioned, currently only basic authentication is supported (digest authentication support is planned).

Example #8 Setting HTTP Authentication User and Password

  1. // Using basic authentication
  2. $client->setAuth('shahar', 'myPassword!', Zend_Http_Client::AUTH_BASIC);
  4. // Since basic auth is default, you can just do this:
  5. $client->setAuth('shahar', 'myPassword!');
  7. // You can also specify username and password in the URI
  8. $client->setUri('');

Sending Multiple Requests With the Same Client

Zend_Http_Client was also designed specifically to handle several consecutive requests with the same object. This is useful in cases where a script requires data to be fetched from several places, or when accessing a specific HTTP resource requires logging in and obtaining a session cookie, for example.

When performing several requests to the same host, it is highly recommended to enable the 'keepalive' configuration flag. This way, if the server supports keep-alive connections, the connection to the server will only be closed once all requests are done and the Client object is destroyed. This prevents the overhead of opening and closing TCP connections to the server.

When you perform several requests with the same client, but want to make sure all the request-specific parameters are cleared, you should use the resetParameters() method. This ensures that GET and POST parameters, request body and request-specific headers are reset and are not reused in the next request.

Note: Resetting parameters
Note that non-request specific headers are not reset by default when the resetParameters() method is used. Only the 'Content-length' and 'Content-type' headers are reset. This allows you to set-and-forget headers like 'Accept-language' and 'Accept-encoding'
To clean all headers and other data except for URI and method, use resetParameters(true).

Another feature designed specifically for consecutive requests is the Cookie Jar object. Cookie Jars allow you to automatically save cookies set by the server in the first request, and send them on consecutive requests transparently. This allows, for example, going through an authentication request before sending the actual data fetching request.

If your application requires one authentication request per user, and consecutive requests might be performed in more than one script in your application, it might be a good idea to store the Cookie Jar object in the user's session. This way, you will only need to authenticate the user once every session.

Example #9 Performing consecutive requests with one client

  1. // First, instantiate the client
  2. $client = new Zend_Http_Client('', array(
  3.     'keepalive' => true
  4. ));
  6. // Do we have the cookies stored in our session?
  7. if (isset($_SESSION['cookiejar']) &&
  8.     $_SESSION['cookiejar'] instanceof Zend_Http_CookieJar) {
  10.     $client->setCookieJar($_SESSION['cookiejar']);
  11. } else {
  12.     // If we don't, authenticate and store cookies
  13.     $client->setCookieJar();
  14.     $client->setUri('');
  15.     $client->setParameterPost(array(
  16.         'user' => 'shahar',
  17.         'pass' => 'somesecret'
  18.     ));
  19.     $client->request(Zend_Http_Client::POST);
  21.     // Now, clear parameters and set the URI to the original one
  22.     // (note that the cookies that were set by the server are now
  23.     // stored in the jar)
  24.     $client->resetParameters();
  25.     $client->setUri('');
  26. }
  28. $response = $client->request(Zend_Http_Client::GET);
  30. // Store cookies in session, for next page
  31. $_SESSION['cookiejar'] = $client->getCookieJar();

Data Streaming

By default, Zend_Http_Client accepts and returns data as PHP strings. However, in many cases there are big files to be sent or received, thus keeping them in memory might be unnecessary or too expensive. For these cases, Zend_Http_Client supports reading data from files (and in general, PHP streams) and writing data to files (streams).

In order to use stream to pass data to Zend_Http_Client, use setRawData() method with data argument being stream resource (e.g., result of fopen()).

Example #10 Sending file to HTTP server with streaming

  1. $fp = fopen("", "r");
  2. $client->setRawData($fp, 'application/zip')->request('PUT');

Only PUT requests currently support sending streams to HTTP server.

In order to receive data from the server as stream, use setStream(). Optional argument specifies the filename where the data will be stored. If the argument is just TRUE (default), temporary file will be used and will be deleted once response object is destroyed. Setting argument to FALSE disables the streaming functionality.

When using streaming, request() method will return object of class Zend_Http_Client_Response_Stream, which has two useful methods: getStreamName() will return the name of the file where the response is stored, and getStream() will return stream from which the response could be read.

You can either write the response to pre-defined file, or use temporary file for storing it and send it out or write it to another file using regular stream functions.

Example #11 Receiving file from HTTP server with streaming

  1. $client->setStream(); // will use temp file
  2. $response = $client->request('GET');
  3. // copy file
  4. copy($response->getStreamName(), "my/downloads/file");
  5. // use stream
  6. $fp = fopen("my/downloads/file2", "w");
  7. stream_copy_to_stream($response->getStream(), $fp);
  8. // Also can write to known file
  9. $client->setStream("my/downloads/myfile")->request('GET');


© 2006-2018 by Zend, a Rogue Wave Company. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.