How can the CURLOPT_COOKIEJAR option be utilized effectively when working with cookies in PHP using CURL?

When working with cookies in PHP using CURL, the CURLOPT_COOKIEJAR option can be utilized effectively to save received cookies to a file for later use. This option allows the cookies to be stored in a file on the server, which can then be loaded and sent back in subsequent requests to maintain session information.

// Initialize a CURL session
$ch = curl_init();

// Set the URL to send the request to
curl_setopt($ch, CURLOPT_URL, 'https://example.com/api');

// Set the option to save cookies to a file
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

// Execute the request
$response = curl_exec($ch);

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