How can PHP be used to capture and reuse cookies from a remote website?

To capture and reuse cookies from a remote website using PHP, you can use cURL to make a request to the remote website, capture the cookies from the response headers, and then reuse those cookies in subsequent requests to the same website.

<?php
// Initialize cURL session
$ch = curl_init();

// Set the URL of the remote website
$url = 'http://www.example.com';

// Set cURL options to capture cookies
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);

// Execute the cURL session
$response = curl_exec($ch);

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

// Reuse the captured cookies in subsequent requests
// Add the cookies to the cURL request headers
curl_setopt($ch, CURLOPT_COOKIE, http_build_query($cookies, '', '; '));

// Make another request to the remote website with the captured cookies
$response = curl_exec($ch);

// Close the cURL session
curl_close($ch);

// Display the response
echo $response;
?>