What is the purpose of setting a cookie with cURL in PHP?

Setting a cookie with cURL in PHP allows you to maintain a session between multiple HTTP requests. This is useful when you need to access a website that requires authentication or stores session data in cookies. By setting a cookie in cURL, you can pass along the necessary session information to ensure that subsequent requests are treated as part of the same session.

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

// Set cookie with cURL
curl_setopt($ch, CURLOPT_COOKIE, 'session_id=1234567890');

// Set other cURL options and perform request
curl_setopt($ch, CURLOPT_URL, 'https://example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

// Close cURL session
curl_close($ch);