PHP cURL with Sessions

PHP scripts have the ability to request content from other servers using cURL. cURL makes a request to a remote server page, fetches the content and returns it to the script. cURL can make GET and POST requests, retrieving and pushing data respectively, behaving very much like a browser client making requests to a website.

Web browsers employ sessions, however, that provide some kind of memory between requests as to the client’s interactions with the server. Session cookies store information the server instructs the client to store, and these properties are then sent back to the server in the following requests. The server will very often use these to identify a client or provide it with a different experience in terms of page layout or available services.

To emulate this process in PHP with cURL, we can use cURL’s cookies. Take a standard PHP cURL request:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$content = curl_exec($ch);
curl_close($ch);

This code will fetch the remote page using a POST request, but it makes no use of cookies so no session will be kept. To allow cURL to store and send cookies when contacting this server, we’d need to specify a cookie file:

$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
    $fh = fopen($cookieFile, "w");
    fwrite($fh, "");
    fclose($fh);
}

The file must be writeable by the web server of course. Once it’s accessible, adding a couple of new lines to the topmost example will yield cookie functionality:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
$content = curl_exec($ch);
curl_close($ch);

That’s it – all cURL requests using this code will store and send cookies.