Parsing cookies with Zend Http Client and CookieJar

I’ve just run into the need to be able to get the http cookies of a response to a request sent from PHP and accepted in PHP. Normally cookies can be accessed through the $_COOKIE super global but since no client/browser is involved that won’t be possible in this case. The below is an example of machine to machine communication.

Zend Http Client can be used to make the post and then the fromResponse method of Zend Http CookieJar can be used to actually get the cookies.

I also wanted the cookies’ names => values to be available as an associative array, not the standard numerical with one cookie object in each positions. That is what you get when calling getAllCookies on the CookieJar object.

class Ext_Zend_Http_CookieJar extends Zend_Http_CookieJar{
 	public static function fromResponse(Zend_Http_Response $response, $ref_uri){
        $jar = new self();
        $jar->addCookiesFromResponse($response, $ref_uri);
        return $jar;
	function asAssocKeyVal(){
		$rarr = array();
		foreach($this->getAllCookies() as $cookie)
			$rarr[ $cookie->getDomain() ][ $cookie->getName() ] = $cookie->getValue();
		return $rarr;

So in order to accomplish this we extend Zend_Http_CookieJar and put the functionality (asAssocKeyVal) in the extension. However since the original fromResponse method is a static factory function that returns a parent object we need to redefine it in the child too.

The data in each Zend_Http_Cookie object is protected so we use the getDomain, getName and getValue methods to get at it.

Anyway, as you can see the result will be an array that could look like this:

    [.domain1.loc] => Array
            [sessionId] => 123,
            [whatever => something
     [.domain2.loc] => Array
            [sessionId] => 123

$client = new Zend_Http_Client('', array(
    'maxredirects' 	=> 2,
    'timeout'      	=> 30,
	'keepalive'		=> true


$response = $client->request('POST');

$cookiejar = Ext_Zend_Http_CookieJar::fromResponse($response);

$cookies = $cookiejar->asAssocKeyVal();


The above code is an example of how all this can be used to get the cookies like above, not much to add, for more on Zend Http Client see the Parsing with Zend HTTP Client article.

All the above can be tested by adding the following to

setcookie('sessionId', '123', time() + 5, '/', "");

Related Posts

Tags: , , , , ,