How can PHP stream context be used to include additional headers, such as cookies, when fetching content from a website?

When fetching content from a website using PHP, you may need to include additional headers such as cookies for authentication or session management. This can be achieved using PHP stream context, which allows you to set custom headers for HTTP requests. By creating a stream context with the necessary headers and passing it to functions like file_get_contents or fopen, you can include cookies or other headers in your requests.

// URL of the website to fetch content from
$url = 'https://www.example.com';

// Custom headers, such as cookies
$customHeaders = array(
    'Cookie: session_id=1234567890',
);

// Create stream context with custom headers
$contextOptions = array(
    'http' => array(
        'header' => implode("\r\n", $customHeaders),
    ),
);
$context = stream_context_create($contextOptions);

// Fetch content from the website with custom headers
$content = file_get_contents($url, false, $context);

// Output the fetched content
echo $content;