What are some best practices for handling HTTP headers, cookies, and user agent strings when using file_get_contents to access external content in PHP?

When using file_get_contents to access external content in PHP, it's important to handle HTTP headers, cookies, and user agent strings properly to ensure a successful request and response. This can include setting custom headers, managing cookies, and specifying a user agent string to mimic a browser.

$url = 'https://example.com/api';
$options = [
    'http' => [
        'header' => "Content-type: application/json\r\n" .
                    "User-Agent: MyCustomUserAgent\r\n" .
                    "Cookie: cookie1=value1; cookie2=value2\r\n",
        'method' => 'GET'
    ]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

if ($response === false) {
    // Handle error
} else {
    // Process response
}