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

Zend_Http_Cookie: Matching against a scenario

The only real logic contained in a Zend_Http_Cookie object, is in the match() method. This method is used to test a cookie against a given HTTP request scenario, in order to tell whether the cookie should be sent in this request or not. The method has the following syntax and parameters: Zend_Http_Cookie->match(mixed $uri, [boolean $matchSessionCookies, [int $now]]);

  • $uri: A Zend_Uri_Http object with a domain name and path to be checked. Optionally, a string representing a valid HTTP URL can be passed instead. The cookie will match if the URL's scheme (HTTP or HTTPS), domain and path all match.

  • $matchSessionCookies: Whether session cookies should be matched or not. Defaults to TRUE. If set to FALSE, cookies with no expiration time will never match.

  • $now: Time (represented as UNIX time stamp) to check a cookie against for expiration. If not specified, will default to the current time.

Example 501. Matching cookies

<?php
// Create the cookie object - first, a secure session cookie
$cookie Zend_Http_Cookie::fromString('foo=two+words; ' +
                                       
'domain=.example.com; ' +
                                       
'path=/somedir; ' +
                                       
'secure;');

$cookie->match('https://www.example.com/somedir/foo.php');
// Will return true

$cookie->match('http://www.example.com/somedir/foo.php');
// Will return false, because the connection is not secure

$cookie->match('https://otherexample.com/somedir/foo.php');
// Will return false, because the domain is wrong

$cookie->match('https://example.com/foo.php');
// Will return false, because the path is wrong

$cookie->match('https://www.example.com/somedir/foo.php'false);
// Will return false, because session cookies are not matched

$cookie->match('https://sub.domain.example.com/somedir/otherdir/foo.php');
// Will return true

// Create another cookie object - now, not secure, with expiration time
// in two hours
$cookie Zend_Http_Cookie::fromString('foo=two+words; ' +
                                       
'domain=www.example.com; ' +
                                       
'expires='
                                       
date(DATE_COOKIEtime() + 7200));

$cookie->match('http://www.example.com/');
// Will return true

$cookie->match('https://www.example.com/');
// Will return true - non secure cookies can go over secure connections
// as well!

$cookie->match('http://subdomain.example.com/');
// Will return false, because the domain is wrong

$cookie->match('http://www.example.com/'truetime() + (3600));
// Will return false, because we added a time offset of +3 hours to
// current time


Zend Framework