Skip to content
PHP Logo

How can cURL be utilized to handle cookies and authentication in PHP scripts?

When making HTTP requests in PHP scripts using cURL, it may be necessary to handle cookies and authentication to interact with websites that require login credentials or maintain session information. This can be achieved by setting the appropriate cURL options to handle cookies and authentication headers.

php
<?php

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

// Set URL to fetch
curl_setopt($ch, CURLOPT_URL, 'https://example.com');

// Set cURL options for handling cookies and authentication
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');

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

// Close cURL session
curl_close($ch);

// Output the response
echo $response;

?>