PhpRiot
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()

<?php
// 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
$client->setCookie('flavor=chocolate%20chips');

// By providing a Zend_Http_Cookie object
$cookie Zend_Http_Cookie::fromString('flavor=chocolate%20chips');
$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 480. Enabling Cookie Stickiness

<?php
// To turn cookie stickiness on, set a Cookie Jar
$client->setCookieJar();

// First request: log in and start a session
$client->setUri('http://example.com/login.php');
$client->setParameterPost('user''h4x0r');
$client->setParameterPost('password''1337');
$client->request('POST');

// 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.
$client->setUri('http://example.com/read_member_news.php');
$client->request('GET');


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

Zend Framework