Headers

Both request and response messages contain HTTP headers.

Accessing Headers

You can check if a request or response has a specific header using the hasHeader() method.

  1. use GuzzleHttp\Psr7;
  2. $request = new Psr7\Request('GET', '/', ['X-Foo' => 'bar']);
  3. if ($request->hasHeader('X-Foo')) {
  4. echo 'It is there';
  5. }

You can retrieve all the header values as an array of strings using getHeader().

  1. $request->getHeader('X-Foo'); // ['bar']
  2. // Retrieving a missing header returns an empty array.
  3. $request->getHeader('X-Bar'); // []

You can iterate over the headers of a message using the getHeaders() method.

  1. foreach ($request->getHeaders() as $name => $values) {
  2. echo $name . ': ' . implode(', ', $values) . "\r\n";
  3. }

Complex Headers

Some headers contain additional key value pair information. For example, Link headers contain a link and several key value pairs:

  1. <http://foo.com>; rel="thing"; type="image/jpeg"

Guzzle provides a convenience feature that can be used to parse these types of headers:

  1. use GuzzleHttp\Psr7;
  2. $request = new Psr7\Request('GET', '/', [
  3. 'Link' => '<http:/.../front.jpeg>; rel="front"; type="image/jpeg"'
  4. ]);
  5. $parsed = Psr7\parse_header($request->getHeader('Link'));
  6. var_export($parsed);

Will output:

  1. array (
  2. 0 =>
  3. array (
  4. 0 => '<http:/.../front.jpeg>',
  5. 'rel' => 'front',
  6. 'type' => 'image/jpeg',
  7. ),
  8. )

The result contains a hash of key value pairs. Header values that have no key (i.e., the link) are indexed numerically while headers parts that form a key value pair are added as a key value pair.