"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Extract Cookies from a PHP Curl Response into a Variable?

How Can I Extract Cookies from a PHP Curl Response into a Variable?

Posted on 2025-02-07
Browse:507

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3