Cookies

<?php
$requestcookies = array(
'foo' => 'foovalue',
'bar' => 'barvalue'
);

$cookiejar = '/path/to/cookiejar';

// Procedural $options = array(
'cookie' => $requestcookies,
// - OR -
'cookiestore' => $cookiejar
);

$response = http_get('http://localhost.example', $options); $parsedresponse = http_parse_message($response);
$responsecookies = array_map(
'http_pa rse_cookie',
$parsedresponse->headers['Set-Cookie']
);

// Object-oriented
$request = new HttpRequest('http://localhost.example');
$request->enableCookies();
$request->setCookies($cookies);
$request->addCookies(array('baz' => 'bazvalue'));
$request->send();
$responsecookies = $request->getResponseCookies();
?>
  • Like cURL, pecl_http allows cookie data to be specified manually. Unlike cURL, pecl_http handles most of the formatting for you. Simply specify an associative array of cookie name-value pairs for the ' cookie’ request option. If your cookie values are already encoded, set the ' encodecookies’ request option to false.
  • Also like cURL, pecl_http includes an option to use a file for storing cookie data. Unlike cURL, pecl_http always uses the same data source for both read and write operations. That is, it consolidates the CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR options into the 'cookiestore’ request option.
  • Because the procedural API lacks the persistent scope that is a defining characteristic of the object-oriented API, extracting cookie values for uses beyond storage and persistence is somewhat involved. http_parse_message is used to parse the headers and body from a string containing an HTTP response message into an object for easier access. http_parse_cookie is then applied to Set-Cookie header values to parse the cookie data from them.
  • In HttpRequest the enableCookies method explicitly sets CURLOPT_COOKIEFILE to an empty string so that cookie data is persisted in memory. setCookies accepts an associative array of cookie name-value pairs just like the 'cookie’ request option. addCookies does the same thing, but merges the array contents into any existing cookie data rather than deleting the latter as setCookies does.
  • Once the send method is called on $request, cookie data from the response is retrieved by calling the getResponseCookies method.

© pecl_http PECL Extension — Web Scraping

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