Home >Backend Development >PHP Tutorial >How Can I Extract Cookies from a PHP Curl Response into a Variable?
Retrieving Cookies from PHP Curl Response into a Variable
In certain scenarios, external API responses may be inexplicably embedded as cookies within the HTTP header, instead of utilizing conventional communication protocols like SOAP or REST. To facilitate the extraction of these cookies into a structured array without resorting to laborious parsing, the following technique can be employed.
Utilizing the PHP Curl extension, you can retrieve the HTTP response, including the cookies, using the following code:
$ch = curl_init('http://www.google.com/'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Retrieve headers too curl_setopt($ch, CURLOPT_HEADER, 1); $result = curl_exec($ch);
To extract the cookies from the response, regular expressions can be employed:
// Extract cookies using regular expressions preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches);
The $matches array will contain all the cookies found in the response. To convert this into a more useful format, each cookie string can be parsed into an array using parse_str:
$cookies = array(); foreach($matches[1] as $item) { parse_str($item, $cookie); $cookies = array_merge($cookies, $cookie); }
Finally, you can access the cookies in the $cookies array. This approach effectively extracts cookies from the curl response without the need for complex parsing or file-based operations.
The above is the detailed content of How Can I Extract Cookies from a PHP Curl Response into a Variable?. For more information, please follow other related articles on the PHP Chinese website!