Home >Backend Development >PHP Tutorial >How to Efficiently Extract Cookies from a PHP cURL Response?
When handling unconventional communication protocols like cookie-embedded responses, extracting cookies efficiently can be a challenge. This article tackles this issue by providing a simple solution without the need for writing to a file or tedious parsing.
$ch = curl_init('http://www.google.com/'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // Retrieve headers along with the response curl_setopt($ch, CURLOPT_HEADER, 1); $result = curl_exec($ch); // Extract cookies using regular expression preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $result, $matches); // Convert cookies to an array $cookies = array(); foreach ($matches[1] as $item) { parse_str($item, $cookie); $cookies = array_merge($cookies, $cookie); } // Print the collected cookies var_dump($cookies);
The above is the detailed content of How to Efficiently Extract Cookies from a PHP cURL Response?. For more information, please follow other related articles on the PHP Chinese website!