Zend Framework 2
  • Overview
  • Installation
  • Learning Dependency Injection
    • Very brief introduction to Di.
    • Very brief introduction to Di Container.
    • Simplest usage case (2 classes, one consumes the other)
    • Simplest Usage Case Without Type-hints
    • Simplest usage case with Compiled Definition
    • Creating a precompiled definition for others to use
    • Using Multiple Definitions From Multiple Sources
    • Generating Service Locators
  • Introduction
    • Adapters
    • Results
    • Identity Persistence
    • Usage
  • Database Table Authentication
    • Introduction
    • Advanced Usage: Persisting a DbTable Result Object
    • Advanced Usage By Example
  • Digest Authentication
    • Introduction
    • Specifics
    • Identity
  • HTTP Authentication Adapter
    • Introduction
    • Design Overview
    • Configuration Options
    • Resolvers
    • Basic Usage
  • LDAP Authentication
    • Introduction
    • Usage
    • The API
    • Server Options
    • Collecting Debugging Messages
    • Common Options for Specific Servers
  • Introduction
  • Barcode creation using Zend\Barcode\Barcode class
    • Using Zend\Barcode\Barcode::factory
    • Drawing a barcode
    • Renderering a barcode
  • Zend\Barcode\Barcode Objects
    • Common Options
    • Common Additional Getters
  • Description of shipped barcodes
    • Zend\Barcode\Object\Error
    • Zend\Barcode\Object\Code128
    • Zend\Barcode\Object\Codabar
    • Zend\Barcode\Object\Code25
    • Zend\Barcode\Object\Code25interleaved
    • Zend\Barcode\Object\Ean2
    • Zend\Barcode\Object\Ean5
    • Zend\Barcode\Object\Ean8
    • Zend\Barcode\Object\Ean13
    • Zend\Barcode\Object\Code39
    • Zend\Barcode\Object\Identcode
    • Zend\Barcode\Object\Itf14
    • Zend\Barcode\Object\Leitcode
    • Zend\Barcode\Object\Planet
    • Zend\Barcode\Object\Postnet
    • Zend\Barcode\Object\Royalmail
    • Zend\Barcode\Object\Upca
    • Zend\Barcode\Object\Upce
  • Zend\Barcode Renderers
    • Common Options
    • Zend\Barcode\Renderer\Image
    • Zend\Barcode\Renderer\Pdf
  • The Theory of Caching
    • The Zend_Cache Factory Method
    • Tagging Records
    • Cleaning the Cache
  • Introduction
  • Zend_Cache Frontends
    • Zend_Cache_Core
    • Zend_Cache_Frontend_Output
    • Zend_Cache_Frontend_Function
    • Zend_Cache_Frontend_Class
    • Zend_Cache_Frontend_File
    • Zend_Cache_Frontend_Page
    • Zend_Cache_Frontend_Capture
  • Zend\Cache\Storage\Adapter
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • TODO: Examples
  • Zend\Cache\Storage\Capabilities
    • Overview
    • Available Methods
    • Examples
  • Zend\Cache\Storage\Plugin
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • TODO: Examples
  • Zend\Cache\Pattern
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • Introduction
  • Captcha Operation
  • CAPTCHA Adapters
    • Zend\Captcha\Word
    • Zend\Captcha\Dumb
    • Zend\Captcha\Figlet
    • Zend\Captcha\Image
    • Zend\Captcha\ReCaptcha
  • Introduction
  • Theory of Operation
  • Zend\Config\Reader
    • Zend\Config\Reader\Ini
    • Zend\Config\Reader\Xml
    • Zend\Config\Reader\Json
    • Zend\Config\Reader\Yaml
  • Zend\Config\Writer
    • Zend\Config\Writer\Ini
    • Zend\Config\Writer\Xml
    • Zend\Config\Writer\PhpArray
    • Zend\Config\Writer\Json
    • Zend\Config\Writer\Yaml
  • Zend\Config\Processor
    • Zend\Config\Processor\Constant
    • Zend\Config\Processor\Filter
    • Zend\Config\Processor\Queue
    • Zend\Config\Processor\Token
    • Zend\Config\Processor\Translator
  • Introduction
  • Encrypt/decrypt using block ciphers
  • Key derivation function
  • Password secure storing
  • Zend\Db\Adapter
    • Creating an Adapter (Quickstart)
    • Creating an Adapter (By Injecting Dependencies)
    • Query Preparation Through Zend\Db\Adapter\Adapter::query()
    • Query Execution Through Zend\Db\Adapter\Adapter::query()
    • Creating Statements
    • Using The Platform Object
    • Using The Parameter Container
    • Examples
  • Zend\Db\ResultSet
    • Quickstart
    • Zend\Db\ResultSet\HydratingResultSet
  • Zend\Db\Sql
    • Zend\Db\Sql\Sql (Quickstart)
    • Zend\Db\Sql’s Select, Insert, Update and Delete
    • Zend\Db\Sql\Select
    • Zend\Db\Sql\Insert
    • Zend\Db\Sql\Update
    • Zend\Db\Sql\Delete
    • Zend\Db\Sql\Where & Zend\Db\Sql\Having
  • Zend\Db\TableGateway
    • Basic Usage
    • TableGateway Features
  • Zend\Db\RowGateway
    • Quickstart
  • Zend\Db\Metadata
    • Basic Usage
  • Introduction to Zend\Di
    • Dependency Injection
    • Dependency Injection Containers
  • Zend\Di Quickstart
  • Zend\Di Definition
    • DefinitionList
    • RuntimeDefinition
    • CompilerDefinition
    • ClassDefinition
  • Zend\Di InstanceManager
    • Parameters
    • Preferences
    • Aliases
  • Zend\Di Configuration
  • Zend\Di Debugging & Complex Use Cases
    • Debugging a DiC
    • Complex Use Cases
  • Introduction
  • Zend\Dom\Query
    • Theory of Operation
    • Methods Available
  • The EventManager
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • Introduction to Zend\Form
  • Zend\Form Quick Start
  • Zend\Form\Element
    • Available Methods
  • Zend\Form\Element\Captcha
    • Available Methods
  • Zend\Form\Element\Color
    • Available Methods
  • Zend\Form\Element\Csrf
    • Available Methods
  • Zend\Form\Element\Date
    • Available Methods
  • Zend\Form\Element\DateTimeLocal
    • Available Methods
  • Zend\Form\Element\DateTime
    • Available Methods
  • Zend\Form\Element\Email
    • Available Methods
  • Zend\Form\Element\Month
    • Available Methods
  • Zend\Form\Element\Number
    • Available Methods
  • Zend\Form\Element\Range
    • Available Methods
  • Zend\Form\Element\Time
    • Available Methods
  • Zend\Form\Element\Url
    • Available Methods
  • Zend\Form\Element\Week
    • Available Methods
  • Zend\Http
    • Overview
    • Zend\Http Request, Response and Headers
  • Zend\Http\Request
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • Zend\Http\Response
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • Zend\Http\Headers And The Various Header Classes
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
    • Zend\Http\Header\* Base Methods
    • List of Http Header Types
  • Zend_Http_Cookie and Zend_Http_CookieJar
    • Introduction
    • Instantiating Zend_Http_Cookie Objects
    • Zend_Http_Cookie getter methods
    • Zend_Http_Cookie: Matching against a scenario
    • The Zend_Http_CookieJar Class: Instantiation
    • Adding Cookies to a Zend_Http_CookieJar object
    • Retrieving Cookies From a Zend_Http_CookieJar object
  • Zend\Http\Client
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • Zend_Http_Client - Connection Adapters
    • Overview
    • The Socket Adapter
    • The Proxy Adapter
    • The cURL Adapter
    • The Test Adapter
    • Creating your own connection adapters
  • Zend_Http_Client - Advanced Usage
    • HTTP Redirections
    • Adding Cookies and Using Cookie Persistence
    • Setting Custom Request Headers
    • File Uploads
    • Sending Raw POST Data
    • HTTP Authentication
    • Sending Multiple Requests With the Same Client
    • Data Streaming
  • Translating
    • Adding translations
    • Supported formats
    • Setting a locale
    • Translating messages
    • Caching
  • I18n View Helpers
    • Introduction
  • CurrencyFormat Helper
  • DateFormat Helper
  • NumberFormat Helper
  • Translate Helper
  • TranslatePlural Helper
  • I18n Filters
  • Alnum Filter
  • Alpha Filter
  • NumberFormat Filter
  • Introduction
  • Introduction
    • Theory of operation
  • API overview
    • Configuration / options
    • API Reference
  • Zend\Ldap\Ldap
    • Zend\Ldap\Collection
  • Zend\Ldap\Attribute
  • Zend\Ldap\Converter\Converter
  • Zend\Ldap\Dn
  • Zend\Ldap\Filter
  • Zend\Ldap\Node
  • Zend\Ldap\Node\RootDse
    • OpenLDAP
    • ActiveDirectory
    • eDirectory
  • Zend\Ldap\Node\Schema
    • OpenLDAP
    • ActiveDirectory
  • Zend\Ldap\Ldif\Encoder
  • Usage Scenarios
    • Authentication scenarios
    • Basic CRUD operations
    • Extended operations
  • Tools
    • Creation and modification of DN strings
    • Using the filter API to create search filters
    • Modify LDAP entries using the Attribute API
  • Object oriented access to the LDAP tree using Zend\Ldap\Node
    • Basic CRUD operations
    • Extended operations
    • Tree traversal
  • Getting information from the LDAP server
    • RootDSE
    • Schema Browsing
  • Serializing LDAP data to and from LDIF
    • Serialize a LDAP entry to LDIF
    • Deserialize a LDIF string into a LDAP entry
  • The AutoloaderFactory
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • The PluginClassLoader
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • The ShortNameLocator Interface
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • The PluginClassLocator interface
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • The SplAutoloader Interface
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • The ClassMapAutoloader
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • The StandardAutoloader
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • The Class Map Generator utility: bin/classmap_generator.php
    • Overview
    • Quick Start
    • Configuration Options
  • The PrefixPathLoader
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • The PrefixPathMapper Interface
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • Zend\Mail\Message
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • Zend\Mail\Transport
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • Zend\Mail\Transport\SmtpOptions
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • Zend\Mail\Transport\FileOptions
    • Overview
    • Quick Start
    • Configuration Options
    • Available Methods
    • Examples
  • Introduction to the Module System
    • The autoload_*.php Files
  • The Module Manager
    • Module Manager Events
    • Module Manager Listeners
  • The Module Class
    • The “loadModules.post” Event
    • The MVC “bootstrap” Event
  • The Module Autoloader
    • Module Autoloader Usage
    • Non-Standard / Explicit Module Paths
    • Packaging Modules with Phar
  • Best Practices when Creating Modules
  • Introduction to the MVC Layer
    • Basic Application Structure
    • Basic Module Structure
    • Bootstrapping an Application
    • Bootstrapping a Modular Application
    • Conclusion
  • Quick Start
    • Install the Zend Skeleton Application
    • Create a new module
    • Update the Module class
    • Create a Controller
    • Create a view script
    • Create a route
    • Tell the application about our module
    • Test it out!
  • Default Services
    • ServiceManagerConfiguration
    • ViewManager
    • Application Configuration Options
    • Default Configuration Options
  • Routing
    • Router Types
    • Route Types
  • The MvcEvent
  • Available Controllers
    • Common Interfaces Used With Controllers
    • The AbstractActionController
    • The AbstractRestfulController
  • Controller Plugins
    • The FlashMessenger
    • The Forward Plugin
    • The Post/Redirect/Get Plugin
    • The Redirect Plugin
    • The Url Plugin
  • Examples
    • Controllers
    • Bootstrapping
  • Introduction
    • Resources
    • Roles
    • Creating the Access Control List
    • Registering Roles
    • Defining Access Controls
    • Querying an ACL
  • Refining Access Controls
    • Precise Access Controls
    • Removing Access Controls
  • Advanced Usage
    • Storing ACL Data for Persistence
    • Writing Conditional ACL Rules with Assertions
  • Zend\ServiceManager
  • Zend\ServiceManager Quick Start
    • Using Configuration
    • Modules as Service Providers
    • Examples
  • Zend\Stdlib\Hydrator
    • HydratorInterface
    • Usage
    • Available Implementations
  • Zend_Uri
    • Overview
    • Creating a New URI
    • Manipulating an Existing URI
    • URI Validation
    • Common Instance Methods
  • Introduction
    • What is a validator?
    • Basic usage of validators
    • Customizing messages
    • Translating messages
  • Standard Validation Classes
  • Alnum
    • Supported options for Zend\Validator\Alnum
    • Basic usage
    • Using whitespaces
    • Using different languages
  • Alpha
    • Supported options for Zend\Validator\Alpha
    • Basic usage
    • Using whitespaces
    • Using different languages
  • Barcode
    • Supported options for Zend\Validator\Barcode
    • Basic usage
    • Optional checksum
    • Writing custom adapters
  • Between
    • Supported options for Zend\Validator\Between
    • Default behaviour for Zend\Validator\Between
    • Validation exclusive the border values
  • Callback
    • Supported options for Zend\Validator\Callback
    • Basic usage
    • Usage with closures
    • Usage with class-based callbacks
    • Adding options
  • CreditCard
    • Supported options for Zend\Validator\CreditCard
    • Basic usage
    • Accepting defined credit cards
    • Validation by using foreign APIs
    • Ccnum
  • Date
    • Supported options for Zend\Validator\Date
    • Default date validation
    • Localized date validation
    • Self defined date validation
  • Db\RecordExists and Db\NoRecordExists
    • Supported options for Zend\Validator\Db_*
    • Basic usage
    • Excluding records
    • Database Adapters
    • Database Schemas
  • Digits
    • Supported options for Zend\Validator\Digits
    • Validating digits
  • EmailAddress
    • Basic usage
    • Options for validating Email Addresses
    • Complex local parts
    • Validating only the local part
    • Validating different types of hostnames
    • Checking if the hostname actually accepts email
    • Validating International Domains Names
    • Validating Top Level Domains
    • Setting messages
  • Float
    • Supported options for Zend\Validator\Float
    • Simple float validation
    • Localized float validation
  • GreaterThan
    • Supported options for Zend\Validator\GreaterThan
    • Basic usage
    • Validation inclusive the border value
  • Hex
    • Supported options for Zend\Validator\Hex
  • Hostname
    • Supported options for Zend\Validator\Hostname
    • Basic usage
    • Validating different types of hostnames
    • Validating International Domains Names
    • Validating Top Level Domains
  • Iban
    • Supported options for Zend\Validator\Iban
    • IBAN validation
  • Identical
    • Supported options for Zend\Validator\Identical
    • Basic usage
    • Identical objects
    • Form elements
    • Strict validation
    • Configuration
  • InArray
    • Supported options for Zend\Validator\InArray
    • Simple array validation
    • Array validation modes
    • Recursive array validation
  • Int
    • Supported options for Zend\Validator\Int
    • Simple integer validation
    • Localized integer validation
  • Ip
    • Supported options for Zend\Validator\Ip
    • Basic usage
    • Validate IPv4 or IPV6 alone
  • Isbn
    • Supported options for Zend\Validator\Isbn
    • Basic usage
    • Setting an explicit ISBN validation type
    • Specifying a separator restriction
  • LessThan
    • Supported options for Zend\Validator\LessThan
    • Basic usage
    • Validation inclusive the border value
  • NotEmpty
    • Supported options for Zend\Validator\NotEmpty
    • Default behaviour for Zend\Validator\NotEmpty
    • Changing behaviour for Zend\Validator\NotEmpty
  • PostCode
    • Constructor options
    • Supported options for Zend\Validator\PostCode
  • Regex
    • Supported options for Zend\Validator\Regex
    • Validation with Zend\Validator\Regex
    • Pattern handling
  • Sitemap Validators
    • Sitemap\Changefreq
    • Sitemap\Lastmod
    • Sitemap\Loc
    • Sitemap\Priority
    • Supported options for Zend\Validator\Sitemap_*
  • Step
    • Supported options for Zend\Validator\Step
    • Basic usage
    • Using floating-point values
  • StringLength
    • Supported options for Zend\Validator\StringLength
    • Default behaviour for Zend\Validator\StringLength
    • Limiting the maximum allowed length of a string
    • Limiting the minimal required length of a string
    • Limiting a string on both sides
    • Encoding of values
  • Validator Chains
  • Writing Validators
  • Validation Messages
    • Using pre-translated validation messages
    • Limit the size of a validation message
  • Zend\View Quick Start
    • Overview
    • Usage
  • The PhpRenderer
    • Usage
    • Options and Configuration
    • Additional Methods
  • PhpRenderer View Scripts
    • Escaping Output
  • View Helpers
    • Included Helpers
  • Action View Helper
  • BaseUrl Helper
  • Cycle Helper
  • Partial Helper
  • Placeholder Helper
    • Concrete Placeholder Implementations
  • Doctype Helper
  • HeadLink Helper
  • HeadMeta Helper
  • HeadScript Helper
  • HeadStyle Helper
  • HeadTitle Helper
  • HTML Object Helpers
  • InlineScript Helper
  • JSON Helper
  • Navigation Helpers
    • Translation of labels and titles
    • Integration with ACL
    • Navigation setup used in examples
    • Breadcrumbs Helper
    • Links Helper
    • Menu Helper
    • Sitemap Helper
    • Navigation Helper
    • Registering Helpers
    • Writing Custom Helpers
    • Registering Concrete Helpers
  • Introduction
  • Zend\XmlRpc\Client
    • Introduction
    • Method Calls
    • Types and Conversions
    • Server Proxy Object
    • Error Handling
    • Server Introspection
    • From Request to Response
    • HTTP Client and Testing
  • Zend\XmlRpc\Server
    • Introduction
    • Basic Usage
    • Server Structure
    • Anatomy of a webservice
    • Conventions
    • Utilizing Namespaces
    • Custom Request Objects
    • Custom Responses
    • Handling Exceptions via Faults
    • Caching Server Definitions Between Requests
    • Usage Examples
    • Performance optimization
  • Copyright Information
 
Zend Framework 2
  • Docs »
  • Zend_Http_Cookie and Zend_Http_CookieJar
  • Edit on GitHub

Zend_Http_Cookie and Zend_Http_CookieJar¶

Introduction¶

Zend_Http_Cookie, as expected, is a class that represents an HTTP cookie. It provides methods for parsing HTTP response strings, collecting cookies, and easily accessing their properties. It also allows checking if a cookie matches against a specific scenario, IE a request URL, expiration time, secure connection, etc.

Zend_Http_CookieJar is an object usually used by Zend_Http_Client to hold a set of Zend_Http_Cookie objects. The idea is that if a Zend_Http_CookieJar object is attached to a Zend_Http_Client object, all cookies going from and into the client through HTTP requests and responses will be stored by the CookieJar object. Then, when the client will send another request, it will first ask the CookieJar object for all cookies matching the request. These will be added to the request headers automatically. This is highly useful in cases where you need to maintain a user session over consecutive HTTP requests, automatically sending the session ID cookies when required. Additionally, the Zend_Http_CookieJar object can be serialized and stored in $_SESSION when needed.

Instantiating Zend_Http_Cookie Objects¶

Instantiating a Cookie object can be done in two ways:

  • Through the constructor, using the following syntax: new Zend_Http_Cookie(string $name, string $value, string $domain, [int $expires, [string $path, [boolean $secure]]]);

    • $name: The name of the cookie (eg. ‘PHPSESSID’) (required)
    • $value: The value of the cookie (required)
    • $domain: The cookie’s domain (eg. ‘.example.com’) (required)
    • $expires: Cookie expiration time, as UNIX time stamp (optional, defaults to NULL). If not set, cookie will be treated as a ‘session cookie’ with no expiration time.
    • $path: Cookie path, eg. ‘/foo/bar/’ (optional, defaults to ‘/’)
    • $secure: Boolean, Whether the cookie is to be sent over secure (HTTPS) connections only (optional, defaults to boolean FALSE)
  • By calling the fromString($cookieStr, [$refUri, [$encodeValue]]) static method, with a cookie string as represented in the ‘Set-Cookie ‘HTTP response header or ‘Cookie’HTTP request header. In this case, the cookie value must already be encoded. When the cookie string does not contain a ‘domain’ part, you must provide a reference URI according to which the cookie’s domain and path will be set.

    The fromString() method accepts the following parameters:

    • $cookieStr: a cookie string as represented in the ‘Set-Cookie’HTTP response header or ‘Cookie’HTTP request header (required)
    • $refUri: a reference URI according to which the cookie’s domain and path will be set. (optional, defaults to parsing the value from the $cookieStr)
    • $encodeValue: If the value should be passed through urldecode. Also effects the cookie’s behavior when being converted back to a cookie string. (optional, defaults to true)

    Instantiating a Zend_Http_Cookie object

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    // First, using the constructor. This cookie will expire in 2 hours
    $cookie = new Zend_Http_Cookie('foo',
                                   'bar',
                                   '.example.com',
                                   time() + 7200,
                                   '/path');
    
    // You can also take the HTTP response Set-Cookie header and use it.
    // This cookie is similar to the previous one, only it will not expire, and
    // will only be sent over secure connections
    $cookie = Zend_Http_Cookie::fromString('foo=bar; domain=.example.com; ' .
                                           'path=/path; secure');
    
    // If the cookie's domain is not set, you have to manually specify it
    $cookie = Zend_Http_Cookie::fromString('foo=bar; secure;',
                                           'http://www.example.com/path');
    

Note

When instantiating a cookie object using the Zend_Http_Cookie::fromString() method, the cookie value is expected to be URL encoded, as cookie strings should be. However, when using the constructor, the cookie value string is expected to be the real, decoded value.

A cookie object can be transferred back into a string, using the __toString() magic method. This method will produce a HTTP request “Cookie” header string, showing the cookie’s name and value, and terminated by a semicolon (‘;’). The value will be URL encoded, as expected in a Cookie header:

Stringifying a Zend_Http_Cookie object

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// Create a new cookie
$cookie = new Zend_Http_Cookie('foo',
                               'two words',
                               '.example.com',
                               time() + 7200,
                               '/path');

// Will print out 'foo=two+words;' :
echo $cookie->__toString();

// This is actually the same:
echo (string) $cookie;

// In PHP 5.2 and higher, this also works:
echo $cookie;

Zend_Http_Cookie getter methods¶

Once a Zend_Http_Cookie object is instantiated, it provides several getter methods to get the different properties of the HTTP cookie:

  • getName(): Get the name of the cookie
  • getValue(): Get the real, decoded value of the cookie
  • getDomain(): Get the cookie’s domain
  • getPath(): Get the cookie’s path, which defaults to ‘/’
  • getExpiryTime(): Get the cookie’s expiration time, as UNIX time stamp. If the cookie has no expiration time set, will return NULL.

Additionally, several boolean tester methods are provided:

  • isSecure(): Check whether the cookie is set to be sent over secure connections only. Generally speaking, if TRUE the cookie should only be sent over HTTPS.

  • isExpired(int $time = null): Check whether the cookie is expired or not. If the cookie has no expiration time, will always return TRUE. If $time is provided, it will override the current time stamp as the time to check the cookie against.

  • isSessionCookie(): Check whether the cookie is a “session cookie” - that is a cookie with no expiration time, which is meant to expire when the session ends.

    Using getter methods with Zend_Http_Cookie

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    // First, create the cookie
    $cookie =
        Zend_Http_Cookie::fromString('foo=two+words; ' +
                                     'domain=.example.com; ' +
                                     'path=/somedir; ' +
                                     'secure; ' +
                                     'expires=Wednesday, 28-Feb-05 20:41:22 UTC');
    
    echo $cookie->getName();   // Will echo 'foo'
    echo $cookie->getValue();  // will echo 'two words'
    echo $cookie->getDomain(); // Will echo '.example.com'
    echo $cookie->getPath();   // Will echo '/'
    
    echo date('Y-m-d', $cookie->getExpiryTime());
    // Will echo '2005-02-28'
    
    echo ($cookie->isExpired() ? 'Yes' : 'No');
    // Will echo 'Yes'
    
    echo ($cookie->isExpired(strtotime('2005-01-01') ? 'Yes' : 'No');
    // Will echo 'No'
    
    echo ($cookie->isSessionCookie() ? 'Yes' : 'No');
    // Will echo 'No'
    

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.

    Matching cookies

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    // 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_COOKIE, time() + 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/', true, time() + (3 * 3600));
    // Will return false, because we added a time offset of +3 hours to
    // current time
    

The Zend_Http_CookieJar Class: Instantiation¶

In most cases, there is no need to directly instantiate a Zend_Http_CookieJar object. If you want to attach a new cookie jar to your Zend_Http_Client object, just call the Zend_Http_Client->setCookieJar() method, and a new, empty cookie jar will be attached to your client. You could later get this cookie jar using Zend_Http_Client->getCookieJar().

If you still wish to manually instantiate a CookieJar object, you can do so by calling “new Zend_Http_CookieJar()” directly - the constructor method does not take any parameters. Another way to instantiate a CookieJar object is to use the static Zend_Http_CookieJar::fromResponse() method. This method takes two parameters: a Zend_Http_Response object, and a reference URI, as either a string or a Zend_Uri_Http object. This method will return a new Zend_Http_CookieJar object, already containing the cookies set by the passed HTTP response. The reference URI will be used to set the cookie’s domain and path, if they are not defined in the Set-Cookie headers.

Adding Cookies to a Zend_Http_CookieJar object¶

Usually, the Zend_Http_Client object you attached your CookieJar object to will automatically add cookies set by HTTP responses to your jar. if you wish to manually add cookies to your jar, this can be done by using two methods:

  • Zend_Http_CookieJar->addCookie($cookie[, $ref_uri]): Add a single cookie to the jar. $cookie can be either a Zend_Http_Cookie object or a string, which will be converted automatically into a Cookie object. If a string is provided, you should also provide $ref_uri - which is a reference URI either as a string or Zend_Uri_Http object, to use as the cookie’s default domain and path.
  • Zend_Http_CookieJar->addCookiesFromResponse($response, $ref_uri): Add all cookies set in a single HTTP response to the jar. $response is expected to be a Zend_Http_Response object with Set-Cookie headers. $ref_uri is the request URI, either as a string or a Zend_Uri_Http object, according to which the cookies’ default domain and path will be set.

Retrieving Cookies From a Zend_Http_CookieJar object¶

Just like with adding cookies, there is usually no need to manually fetch cookies from a CookieJar object. Your Zend_Http_Client object will automatically fetch the cookies required for an HTTP request for you. However, you can still use 3 provided methods to fetch cookies from the jar object: getCookie(), getAllCookies(), and getMatchingCookies(). Additionnaly, iterating over the CookieJar will let you retrieve all the Zend_Http_Cookie objects from it.

It is important to note that each one of these methods takes a special parameter, which sets the return type of the method. This parameter can have 3 values:

  • Zend_Http_CookieJar::COOKIE_OBJECT: Return a Zend_Http_Cookie object. If the method returns more than one cookie, an array of objects will be returned.
  • Zend_Http_CookieJar::COOKIE_STRING_ARRAY: Return cookies as strings, in a “foo=bar” format, suitable for sending in a HTTP request “Cookie” header. If more than one cookie is returned, an array of strings is returned.
  • Zend_Http_CookieJar::COOKIE_STRING_CONCAT: Similar to COOKIE_STRING_ARRAY, but if more than one cookie is returned, this method will concatenate all cookies into a single, long string separated by semicolons (;), and return it. This is especially useful if you want to directly send all matching cookies in a single HTTP request “Cookie” header.

The structure of the different cookie-fetching methods is described below:

  • Zend_Http_CookieJar->getCookie($uri, $cookie_name[, $ret_as]): Get a single cookie from the jar, according to its URI (domain and path) and name. $uri is either a string or a Zend_Uri_Http object representing the URI. $cookie_name is a string identifying the cookie name. $ret_as specifies the return type as described above. $ret_type is optional, and defaults to COOKIE_OBJECT.

  • Zend_Http_CookieJar->getAllCookies($ret_as): Get all cookies from the jar. $ret_as specifies the return type as described above. If not specified, $ret_type defaults to COOKIE_OBJECT.

  • Zend_Http_CookieJar->getMatchingCookies($uri[, $matchSessionCookies[, $ret_as[, $now]]]): Get all cookies from the jar that match a specified scenario, that is a URI and expiration time.

    • $uri is either a Zend_Uri_Http object or a string specifying the connection type (secure or non-secure), domain and path to match against.
    • $matchSessionCookies is a boolean telling whether to match session cookies or not. Session cookies are cookies that have no specified expiration time. Defaults to TRUE.
    • $ret_as specifies the return type as described above. If not specified, defaults to COOKIE_OBJECT.
    • $now is an integer representing the UNIX time stamp to consider as “now” - that is any cookies who are set to expire before this time will not be matched. If not specified, defaults to the current time.

    You can read more about cookie matching here: this section.

Next Previous

© Copyright 2012, Zend Technologies Ltd..

Sphinx theme provided by Read the Docs
Edit this document

Edit this document

The source code of this file is hosted on GitHub. Everyone can update and fix errors in this document with few clicks - no downloads needed.

  1. Go to Zend_Http_Cookie and Zend_Http_CookieJar on GitHub.
  2. Edit file contents using GitHub's text editor in your web browser
  3. Fill in the Commit message text box at the end of the page telling why you did the changes. Press Propose file change button next to it when done.
  4. On Send a pull request page you don't need to fill in text anymore. Just press Send pull request button.
  5. Your changes are now queued for review under project's Pull requests tab on GitHub.