Skip to content

Instantly share code, notes, and snippets.

@Bo0m
Created April 7, 2015 20:55
Show Gist options
  • Save Bo0m/e134655760c6d3515190 to your computer and use it in GitHub Desktop.
Save Bo0m/e134655760c6d3515190 to your computer and use it in GitHub Desktop.
Storing cookies from a PHP CURL session outside of the cookie jar.
<?php
/**
* A quick example of storing CURL cookies outside of a local cookie jar file.
* Can be very useful for retaining API sessions between distributed applications.
**/
// Split out cookies from CURL response
function splitCookies($rawResponse, &$cookieData)
{
// Separate header and body
list($curlHeader, $curlBody) = preg_split("/\R\R/", $rawResponse, 2);
// Split out data from Set-Cookie headers
preg_match_all("/^Set-Cookie:\s+(.*);/mU", $curlHeader, $cookieMatchArray);
$cookieData = implode(';', $cookieMatchArray[1]);
return $curlBody;
}
// Example of getting a cookie
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_HEADER, true);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlObj, CURLOPT_URL, "http://127.0.0.1/SendMeSomeCookies");
$responseData = splitCookies(curl_exec($curlObj), $cookieData);
curl_close($curlObj);
// Example of using said cookie in another CURL session
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlObj, CURLOPT_COOKIE, $cookieData);
curl_setopt($curlObj, CURLOPT_URL, "http://127.0.0.1/CookiesRequired");
$responseData = curl_exec($curlObj);
curl_close($curlObj);
?>
@molinto
Copy link

molinto commented Sep 7, 2020

What is inside $cookieData please?

@jeijei4
Copy link

jeijei4 commented Feb 21, 2023

What is inside $cookieData please?

$cookieData is filled in line 15,
this happens thanks to the "&" before the parameter name: &$cookieData,
when calling the function splitCookies the parameter will already be full and can be used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment