Skip to content
PHP Logo

How can PHP scripts handle cookies when accessing external websites?

When accessing external websites, PHP scripts can handle cookies by using the cURL library to send HTTP requests with the necessary cookie information. This involves setting the CURLOPT_COOKIE option in the cURL request to include the cookies received from the external website in subsequent requests.

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

// Set URL to external website
curl_setopt($ch, CURLOPT_URL, 'https://www.externalwebsite.com');

// Enable cookie handling
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');

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

// Close cURL session
curl_close($ch);

// Process response from external website
echo $response;