How can cookies set with cURL be transferred to the browser in PHP?

When using cURL in PHP to make requests to a server, any cookies set by the server are stored in the cURL session and not automatically transferred to the browser. To transfer these cookies to the browser, you can extract them from the cURL response headers and then set them in the browser using the setcookie() function in PHP.

// Make a cURL request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

// Extract cookies from cURL response headers
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $response, $matches);
$cookies = [];
foreach ($matches[1] as $cookie) {
    parse_str($cookie, $cookieArr);
    $cookies = array_merge($cookies, $cookieArr);
}

// Set cookies in the browser
foreach ($cookies as $name => $value) {
    setcookie($name, $value);
}