I wrote this up for Stack Overflow when they were trying out the concept of “Documentation” for all sorts of things. It didn’t work out, but I thought I’d post this somewhere.
cURL can keep cookies received in responses for use with subsequent requests. For simple session cookie handling in memory, this is achieved with a single line of code:
curl_setopt($ch, CURLOPT_COOKIEFILE, "");
In cases where you are required to keep cookies after the cURL handle is destroyed, you can specify the file to store them in:
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookies.txt");
Then, when you want to use them again, pass them as the cookie file:
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookies.txt");
Remember, though, that these two steps are not necessary unless you need to carry cookies between different cURL handles. For most use cases, setting CURLOPT_COOKIEFILE
to the empty string is all you need.
Cookie handling can be used, for example, to retrieve resources from a web site that requires a login. This is typically a two-step procedure. First, POST to the login page.
<?php
# create a cURL handle
$ch = curl_init();
# set the URL (this could also be passed to curl_init() if desired)
curl_setopt($ch, CURLOPT_URL, "https://www.example.com/login.php");
# set the HTTP method to POST
curl_setopt($ch, CURLOPT_POST, true);
# setting this option to an empty string enables cookie handling
# but does not load cookies from a file
curl_setopt($ch, CURLOPT_COOKIEFILE, "");
# set the values to be sent
curl_setopt($ch, CURLOPT_POSTFIELDS, [
"username"=>"joe_bloggs",
"password"=>"$up3r_$3cr3t",
]);
# return the response body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
# send the request
$result = curl_exec($ch);
The second step (after standard error checking is done) is usually a simple GET request. The important thing is to reuse the existing cURL handle for the second request. This ensures the cookies from the first response will be automatically included in the second request.
# we are not calling curl_init()
# simply change the URL
curl_setopt($ch, CURLOPT_URL, "https://www.example.com/show_me_the_foo.php");
# change the method back to GET
curl_setopt($ch, CURLOPT_HTTPGET, true);
# send the request
$result = curl_exec($ch);
# finished with cURL
curl_close($ch);
# do stuff with $result...
This is only intended as an example of cookie handling. In real life, things are usually more complicated. Often you must perform an initial GET of the login page to pull a login token that needs to be included in your POST. Other sites might block the cURL client based on its User-Agent string, requiring you to change it.