Handling Headers

When using the procedural API, limited request header information is available via the $info parameter of functions to issue requests. Response headers are included in the string returned by those function calls. When the string is passed to http_parse_message, it returns an object with a headers property, which is an associative array of header values indexed by header name.

Custom request headers can be set via the 'headers’ request option, which is formatted as an associative array with header names for keys pointing to corresponding header values (as opposed to cURL, which uses an enumerated array with one header name-value pair per array item). Below is an example of custom headers in a request options array.

<?php
$opts = array(
'headers' => array(
'User-Agent' => 'Mozilla/5.0 (X11; U; ...',
'Connection' => 'keep-alive'
)
);
$request = new HttpRequest;
$request->setOptions($opts);
?>

The object-oriented API offers several slightly less cumbersome solutions compared to the procedural API as shown in the examples below.

<?php
$request = new HttpRequest;
// configure $request
$request->send();

// only returns custom set request headers
print_r($request->getHeaders());

// returns all request headers
$requestmessage = $request->getRequestMessage(); print_r($requestmessage->getHeaders());

// returns a specific request header
echo $requestmessage->getHeader('User-Agent');

// both return all response headers
$responsemessage = $request->getResponseMessage(); print_r($responsemessage->getHeaders());
print_r($request->getResponseHeader());

// both return a single response header
echo $responsemessage->getHeader('Content-Length');
echo $request->getResponseHeader('Content-Length');
?>

© pecl_http PECL Extension — Web Scraping

>>> Back to TABLE OF CONTENTS <<<
Category: Article | Added by: Marsipan (31.08.2014)
Views: 398 | Rating: 0.0/0
Total comments: 0
avatar