|
Size: | 64977 |
Storage flags: | no_autoload,compress/gzip (16%) |
The Zend\Http\Headers class is a container for HTTP headers. It is typically accessed as part of a Zend\Http\Request or Zend\Http\Response getHeaders() call. The Headers container will lazily load actual Header objects as to reduce the overhead of header specific parsing.
The Zend\Http\Header\* classes are the domain specific implementations for the various types of Headers that one might encounter during the typical HTTP request. If a header of unknown type is encountered, it will be implemented as a Zend\Http\Header\GenericHeader instance. See the below table for a list of the various HTTP headers and the API that is specific to each header type.
The quickest way to get started interacting with header objects is by getting an already populated Headers container from a request or response object.
1 2 3 4 5 6 7 8 | // $client is an instance of Zend\Http\Client
// You can retrieve the request headers by first retrieving
// the Request object and then calling getHeaders on it
$requestHeaders = $client->getRequest()->getHeaders();
// The same method also works for retrieving Response headers
$responseHeaders = $client->getResponse()->getHeaders();
|
Zend\Http\Headers can also extract headers from a string:
1 2 3 4 5 6 7 8 9 10 11 | $headerString = <<<EOB
Host: www.example.com
Content-Type: text/html
Content-Length: 1337
EOB;
$headers = Zend\Http\Headers::fromString($headerString);
// $headers is now populated with three objects
// (1) Zend\Http\Header\Host
// (2) Zend\Http\Header\ContentType
// (3) Zend\Http\Header\ContentLength
|
Now that you have an instance of Zend\Http\Headers you can manipulate the individual headers it contains using the provided public API methods outlined in the “Available Methods” section.
No configuration options are available.
Headers::fromString(string $string)
Populates headers from string representation
Parses a string for headers, and aggregates them, in order, in the current instance, primarily as strings until they are needed (they will be lazy loaded).
Returns Zend\Http\Headers
setPluginClassLoader(Zend\Loader\PluginClassLocator $pluginClassLoader)
Set an alternate implementation for the plugin class loader
Returns Zend\Http\Headers
getPluginClassLoader()
Return an instance of a Zend\Loader\PluginClassLocator, lazyload and inject map if necessary.
Returns Zend\Loader\PluginClassLocator
addHeaders(array|Traversable $headers)
Add many headers at once
Expects an array (or Traversable object) of type/value pairs.
Returns Zend\Http\Headers
addHeaderLine(string $headerFieldNameOrLine, string $fieldValue)
Add a raw header line, either in name => value, or as a single string ‘name: value’
This method allows for lazy-loading in that the parsing and instantiation of Header object will be delayed until they are retrieved by either get() or current().
Returns Zend\Http\Headers
addHeader(Zend\Http\Header\HeaderInterface $header)
Add a Header to this container, for raw values see addHeaderLine() and addHeaders().
Returns Zend\Http\Headers
removeHeader(Zend\Http\Header\HeaderInterface $header)
Remove a Header from the container
Returns bool
clearHeaders()
Clear all headers
Removes all headers from queue
Returns Zend\Http\Headers
get(string $name)
Get all headers of a certain name/type
Returns false| Zend\Http\Header\HeaderInterface| ArrayIterator
has(string $name)
Test for existence of a type of header
Returns bool
next()
Advance the pointer for this object as an iterator
Returns void
key()
Return the current key for this object as an iterator
Returns mixed
valid()
Is this iterator still valid?
Returns bool
rewind()
Reset the internal pointer for this object as an iterator
Returns void
current()
Return the current value for this iterator, lazy loading it if need be
Returns Zend\Http\Header\HeaderInterface
count()
Return the number of headers in this container. If all headers have not been parsed, actual count could increase if MultipleHeader objects exist in the Request/Response. If you need an exact count, iterate.
Returns int
toString()
Render all headers at once
This method handles the normal iteration of headers; it is up to the concrete classes to prepend with the appropriate status/request line.
Returns string
toArray()
Return the headers container as an array
Returns array
forceLoading()
By calling this, it will force parsing and loading of all headers, after this count() will be accurate
Returns bool
fromString(string $headerLine)
Factory to generate a header object from a string
Returns Zend\Http\Header\GenericHeader
getFieldName()
Retrieve header field name
Returns string
getFieldValue()
Retrieve header field value
Returns string
toString()
Cast to string as a well formed HTTP header line
Returns in form of “NAME: VALUE”
Returns string
parseHeaderLine(string $headerLine)
Parse the given header line and add the values
Returns void
getFieldValuePartsFromHeaderLine(string $headerLine)
Parse the Field Value Parts represented by a header line
Throws Zend\Http\Header\Exception\InvalidArgumentException if the header is invalid
Returns array
getFieldValue(array|null $values = null)
Get field value
Returns string
match(array|string $matchAgainst)
Match a media string against this header. Returns the matched value or false
Returns Accept\FieldValuePart\AcceptFieldValuePart or bool
getPrioritized()
Returns all the keys, values and parameters this header represents
Returns array
static setDateFormat(int $format)
Set date output format.
Returns void
static getDateFormat()
Return current date output format
Returns string
setDate(string|DateTime $date)
Set the date for this header, this can be a string or an instance of DateTime
Throws Zend\Http\Header\Exception\InvalidArgumentException if the date is neither a valid string nor an instance of \DateTime.
Returns self
getDate()
Return date for this header
Returns self
compareTo(string|DateTime $date)
Compare provided date to date for this header. Returns < 0 if date in header is less than $date; > 0 if it’s greater, and 0 if they are equal. See strcmp.
Returns int
date()
Return date for this header as an instance of \DateTime
Returns \DateTime
fromTimestamp(int $time)
Create date-based header from Unix timestamp
Returns self
fromTimeString(string $time)
Create date-based header from strtotime()-compatible string
Returns self
setUri(string|Zend\Uri\UriInterface $uri)
Set the URI/URL for this header, this can be a string or an instance of Zend\Uri\Http
Throws Zend\Http\Header\Exception\InvalidArgumentException if $uri is neither a valid URL nor an instance of Zend\Uri\UriInterface.
Returns self
getUri()
Return the URI for this header
Returns string
uri()
Return the URI for this header as an instance of Zend\Uri\Http
Returns Zend\Uri\UriInterface
Some header classes expose methods for manipulating their value. The following list contains all of the classes available in the Zend\Http\Header\* namespace, as well as any specific methods they contain. All these classes implement Zend\Http\Header\HeaderInterface and its methods.
See Zend\Http\Header\AbstractAccept methods.
Add a media type, with the given priority
Returns self
Does the header have the requested media type?
Returns bool
See Zend\Http\Header\AbstractAccept methods.
Add a charset, with the given priority
Returns self
Does the header have the requested charset?
Returns bool
See Zend\Http\Header\AbstractAccept methods.
Add an encoding, with the given priority
Returns self
Does the header have the requested encoding?
Returns bool
See Zend\Http\Header\AbstractAccept methods.
Add a language, with the given priority
Returns self
Does the header have the requested language?
Returns bool
getRangeUnit()
setRangeUnit($rangeUnit)
Get number of seconds
Returns int
Set number of seconds
Returns self
Get list of all defined methods
Returns array
Get list of allowed methods
Returns array
Allow methods or list of methods
Returns self
Disallow methods or list of methods
Returns self
Convenience alias for disallowMethods()
Returns self
Check whether method is allowed
Returns bool
Checks if the internal directives array is empty
Returns bool
Add a directive
For directives like ‘max-age=60’, $value = ‘60’
For directives like ‘private’, use the default $value = true
Returns self
Check the internal directives array for a directive
Returns bool
Fetch the value of a directive from the internal directive array
Returns string|null
Remove a directive
Returns self
Set arbitrary header value
RFC allows any token as value, ‘close’ and ‘keep-alive’ are commonly used
Returns self
Whether the connection is persistent
Returns bool
Set Connection header to define persistent connection
Returns self
Retrieve the defined directives for the policy
Returns an array
Set the directive with the given name to include the sources
As an example: an auction site wishes to load images from any URI, plugin content from a list of trusted media providers (including a content distribution network), and scripts only from a server under its control hosting sanitized ECMAScript:
// http://www.w3.org/TR/2012/CR-CSP-20121115/#sample-policy-definitions
// Example #2
$csp = new ContentSecurityPolicy();
$csp->setDirective('default-src', array()) // No sources
->setDirective('img-src', array('*'))
->setDirective('object-src' array('media1.example.com', 'media2.example.com', '*.cdn.example.com'))
->setDirective('script-src', array('trustedscripts.example.com'));
Returns self
Determine if the mediatype value in this header matches the provided criteria
Returns bool|string
Get the media type
Returns string
Set the media type
Returns self
Get any additional content-type parameters currently set
Returns array
Set additional content-type parameters
Returns self
Get the content-type character set encoding, if any
Returns string|null
Set the content-type character set encoding
Returns self
Extends ArrayObject
static fromSetCookieArray(array $setCookies)
setEncodeValue()
getEncodeValue()
See Zend\Http\Header\AbstractDate methods.
Set number of seconds
Returns self
Get number of seconds
Returns int
Whether the cookies contains the Secure flag
Returns bool
Set whether the cookies contains the Secure flag
Returns self
Whether the cookies can be accessed via HTTP only
Returns bool
Set whether the cookies can be accessed via HTTP only
Returns self
Whether the cookie is expired
Returns bool
Whether the cookie is a session cookie
Returns bool
Set whether the value for this cookie should be quoted
Returns self
Check whether the value for this cookie should be quoted
Returns bool
Whether the cookie is valid for a given request domain, path and isSecure
Returns bool
Checks whether the cookie should be sent or not in a specific scenario
Returns bool
Check if a cookie’s domain matches a host name.
Returns bool
Check if a cookie’s path matches a URL path
Returns bool
Retrieving headers from a Zend\Http\Headers object
1 2 3 4 5 6 7 8 9 10 11 12 | // $client is an instance of Zend\Http\Client
$response = $client->send();
$headers = $response->getHeaders();
// We can check if the Request contains a specific header by
// using the ``has`` method. Returns boolean ``TRUE`` if at least
// one matching header found, and ``FALSE`` otherwise
$headers->has('Content-Type');
// We can retrieve all instances of a specific header by using
// the ``get`` method:
$contentTypeHeaders = $headers->get('Content-Type');
|
There are three possibilities for the return value of the above call to the get method:
- If no Content-Type header was set in the Request, get will return false.
- If only one Content-Type header was set in the Request, get will return an instance of Zend\Http\Header\ContentType.
- If more than one Content-Type header was set in the Request, get will return an ArrayIterator containing one Zend\Http\Header\ContentType instance per header.
Adding headers to a Zend\Http\Headers object
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 | $headers = new Zend\Http\Headers();
// We can directly add any object that implements Zend\Http\Header\HeaderInterface
$typeHeader = Zend\Http\Header\ContentType::fromString('Content-Type: text/html');
$headers->addHeader($typeHeader);
// We can add headers using the raw string representation, either
// passing the header name and value as separate arguments...
$headers->addHeaderLine('Content-Type', 'text/html');
// .. or we can pass the entire header as the only argument
$headers->addHeaderLine('Content-Type: text/html');
// We can also add headers in bulk using addHeaders, which accepts
// an array of individual header definitions that can be in any of
// the accepted formats outlined below:
$headers->addHeaders(array(
// An object implementing Zend\Http\Header\HeaderInterface
Zend\Http\Header\ContentType::fromString('Content-Type: text/html'),
// A raw header string
'Content-Type: text/html',
// We can also pass the header name as the array key and the
// header content as that array key's value
'Content-Type' => 'text/html');
));
|
Removing headers from a Zend\Http\Headers object
We can remove all headers of a specific type using the removeHeader method, which accepts a single object implementing Zend\Http\Header\HeaderInterface
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // $headers is a pre-configured instance of Zend\Http\Headers
// We can also delete individual headers or groups of headers
$matches = $headers->get('Content-Type');
// If more than one header was found, iterate over the collection
// and remove each one individually
if ($matches instanceof ArrayIterator) {
foreach ($headers as $header) {
$headers->removeHeader($header);
}
// If only a single header was found, remove it directly
} elseif ($matches instanceof Zend\Http\Header\HeaderInterface) {
$headers->removeHeader($header);
}
// In addition to this, we can clear all the headers currently stored in
// the container by calling the clearHeaders() method
$matches->clearHeaders();
|
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.