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;

3. $request = new Psr7\Request('GET', '/', ['X-Foo' => 'bar']);

5. if ($request->hasHeader('X-Foo')) {
6. echo 'It is there';
7. }

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

1. $request->getHeader('X-Foo'); // ['bar']

3. // Retrieving a missing header returns an empty array.
4. $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;

3. $request = new Psr7\Request('GET', '/', [
4. 'Link' => '<http:/.../front.jpeg>; rel="front"; type="image/jpeg"'
5. ]);

7. $parsed = Psr7\parse_header($request->getHeader('Link'));
8. 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.