Extracting Cookies from a PHP cURL Response
Retrieving cookies embedded in HTTP headers can be essential for parsing responses from non-standard communication protocols. To simplify this task, avoid unnecessary file write operations, and potentially save ample time, consider the following solution using PHP's cURL extension:
// Initialize cURL $ch = curl_init('http://www.google.com/'); // Enable response caching and header retrieval curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 1); // Execute cURL request $result = curl_exec($ch); // Extract cookies from header using regular expression (multi-cookie support) 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); } // Display the extracted cookies as an array var_dump($cookies);
This solution effectively extracts cookies from a cURL response using regular expressions and stores them in an associative array. By leveraging PHP's built-in cookie handling capabilities, you can avoid writing to a file and simplify the process of parsing cookies from custom protocols.
The above is the detailed content of How to Extract Cookies from a PHP cURL Response Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!