PHP CURL How to set Cookie Data as variables

I came across this issue when using an API. The API required a login using a username and password. Nothing strange about that. What was interesting though was the fact that you needed a CSRF token for that login generated from a specific CSRF endpoint. Again, fine but if you needed to make subsequent API requests you needed another CSRF token. I guess this makes sense from a security perspective.

I swiftly realised that this token was not being returned in the preceding response packet but was being set in a cookie. Unfortunately PHP has no elegant way of returning a predefined associative array of the cookie data set by CURL. The only way I found to do it was using this solution ( ):

$ch = curl_init('');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// get headers too with this line
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
// get cookie
// multi-cookie variant contributed by @Combuster in comments
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
$cookies = array();
foreach($matches[1] as $item) {
    parse_str($item, $cookie);
    $cookies = array_merge($cookies, $cookie);

What’s happening here?

preg_match_all is doing most of the work here. Its accessing the cookie file set by CURL and retrieving lines the that match the regular expression, essentially anything with characters in it. Next, we have a foreach loop that takes the generated $matches array and loops through it.

The next key function here is parse_str that takes the $item and using the ‘=’ sign as a delimiter it creates an associative array (key/value pairs). Using the array_merge function it adds the element to the $cookies array.

Finally, what we have is an associative array, $cookies, that we can use any where in our code to pull out the relevant cookie information we need. For my purposes that would be the csrf_token.