11.3. Fetching a URL with Cookies

Problem

You want to retrieve a page that requires a cookie to be sent with the request for the page.

Solution

Use the cURL extension and the CURLOPT_COOKIE option:

$c = curl_init('http://www.example.com/needs-cookies.php');
curl_setopt($c, CURLOPT_VERBOSE, 1);
curl_setopt($c, CURLOPT_COOKIE, 'user=ellen; activity=swimming');
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$page = curl_exec($c);
curl_close($c);

If cURL isn’t available, use the addHeader( ) method in the PEAR HTTP_Request class:

require 'HTTP/Request.php';

$r = new HTTP_Request('http://www.example.com/needs-cookies.php');
$r->addHeader('Cookie','user=ellen; activity=swimming');
$r->sendRequest();
$page = $r->getResponseBody();

Discussion

Cookies are sent to the server in the Cookie request header. The cURL extension has a cookie-specific option, but with HTTP_Request, you have to add the Cookie header just as with other request headers. Multiple cookie values are sent in a semicolon-delimited list. The examples in the Solution send two cookies: one named user with value ellen and one named activity with value swimming.

To request a page that sets cookies and then make subsequent requests that include those newly set cookies, use cURL’s “cookie jar” feature. On the first request, set CURLOPT_COOKIEJAR to the name of a file to store the cookies in. On subsequent requests, set CURLOPT_COOKIEFILE to the same filename, and cURL reads the cookies from the file and sends them along with the ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.