Home > Backend Development > PHP Tutorial > How to Efficiently Extract Cookies from a PHP cURL Response?

How to Efficiently Extract Cookies from a PHP cURL Response?

Susan Sarandon
Release: 2024-12-27 16:49:10
Original
1056 people have browsed it

How to Efficiently Extract Cookies from a PHP cURL Response?

Retrieving 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);
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template