Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...

When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

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 479. Setting Cookies Using setCookie()

// Easy and simple: by providing a cookie name and cookie value
$client->setCookie('flavor''chocolate chips');

// By directly providing a raw cookie string (name=value)
// Note that the value must be already URL encoded

// By providing a Zend_Http_Cookie object
$cookie Zend_Http_Cookie::fromString('flavor=chocolate%20chips');

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 480. Enabling Cookie Stickiness

// To turn cookie stickiness on, set a Cookie Jar

// First request: log in and start a session

// The Cookie Jar automatically stores the cookies set
// in the response, like a session ID cookie.

// Now we can send our next request - the stored cookies
// will be automatically sent.

For more information about the Zend_Http_CookieJar class, see this section.

Zend Framework