Home / PHP CURL and Cookies

PHP CURL and Cookies

PHP’s CURL functions make it easy to download content from websites. Sometimes you need to be able to manage cookies set from the site the data is coming from. This is done using the CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE options as shown in this post.

CURLOPT_COOKIEJAR

CURLOPT_COOKIEJAR species the filename where the cookies should be stored. If the server sets any they will be written to this file, and it will be created if it does not already exist.

To set the cookie file as /tmp/cookies.txt (which is not really a good place to store the cookie file, but will serve for this example), to the curl handle $ch:

curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');

CURLOPT_COOKIEFILE

The cookie jar setting is where curl writes cookies to, but a separate setting is required for curl to send cookies back to the server. This is the CURLOPT_COOKIEFILE setting. If it is not set then no cookies will be sent to the server. If the file does not exist, then no error is issued.

Example usage:

curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');

Putting it all together

The following piece of code reads and writes cookies to the /tmp/cookies.txt file when making a request to http://www.example.com:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');

$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);

The HTML from the request is stored in $output and an array of information about the request is stored in the $info variable. I’ve covered these two variables in a couple of my previous posts about PHP and curl.