PHP + Cookies + libCurl
Ever wondered how would you be able to use cookies together with libCurl? I'm going to demonstrate how to do it by providing an example of a website requiring login in order to allow access to its pages.
First of all, we need a temporary file to store the cookies.
$tmpfile = tempnam (sys_get_temp_dir(), "CURLCOOKIE");
Then, we need to tell curl we want to store the cookies in that file.
curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfile);
To quote PHP.net: (for CURLOPTCOOKIEJAR)
"The name of a file to save all internal cookies to when the handle is closed, e.g. after a call to curlclose. "
After running that (along with the rest of your curl code) you'll have cookies saved in your system. However, we need to store $tmpfile somewhere. We're going to store part of it in a cookie so we can find the file at a later point in our system.
setcookie("tmpfile", basename(str_replace("CURLCOOKIE", '', $tmpfile)), time()+7200);
Here's the remote log in curl code: (this is an example, the options may vary depending on what you want to achieve)
$tmpfile = tempnam (sys_get_temp_dir(), "CURLCOOKIE");
// store tmpfile in cookies (TESTING PURPOSES ONLY)
setcookie("tmpfile", basename(str_replace("CURLCOOKIE", '', $tmpfile)), time()+7200);
$curl_result = $curl_err = '';
$req = 'email='.$email.'&password='.$password;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://yourtestwebiste.com/login.php");
curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfile); // if logged in properly, login.php will tell the system which cookies to save and curl will save them in the temporary file $tmpfile
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/x-www-form-urlencoded", "Content-Length: " . strlen($req)));
curl_setopt($ch, CURLOPT_HEADER , 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$curl_result = @curl_exec($ch);
$curl_err = curl_error($ch);
curl_close($ch);
if ($curl_result === false)
die("Error");
else {
// Do something
}
Then if you want to use curl to access another page on that website, you must use:
curl_setopt($ch, CURLOPT_COOKIEFILE, $tmpfile);
instead of: (and change the rest of the curl calls to something that fits your needs)
curl_setopt($ch, CURLOPT_COOKIEJAR, $tmpfile);
and in this case $tmpfile should be:
sys_get_temp_dir().'/CURLCOOKIE'.basename($_COOKIE['tmpfile'])
Although part of the filename is saved in cookies, it can't be manipulated to access undesired directories or files in your system. This is not an ideal solution because it still allows users to manipulate curl to read other cookie files instead. Since the topic is not about cookies, I won't go into much depth regarding this issue.