How can PHP sessions be effectively integrated with cookies in cURL requests?

When making cURL requests in PHP, it can be challenging to maintain session information across multiple requests. One way to effectively integrate PHP sessions with cookies in cURL requests is to manually extract the session ID from the cookie set by the server and pass it along in subsequent requests. This can be achieved by setting the CURLOPT_COOKIEFILE option to a writable file where cURL can store the received cookies, and then setting the CURLOPT_COOKIE option to the same file to send the cookies back to the server in subsequent requests.

// Initialize cURL session
$ch = curl_init();

// Set cURL options
curl_setopt($ch, CURLOPT_URL, 'http://example.com/login.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

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

// Extract session ID from cookie
preg_match('/PHPSESSID=(.*?);/', $response, $matches);
$session_id = $matches[1];

// Make subsequent request with session ID
curl_setopt($ch, CURLOPT_URL, 'http://example.com/profile.php');
curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $session_id);

$response = curl_exec($ch);

// Close cURL session
curl_close($ch);