What are some best practices for handling user-agent headers when making HTTP requests in PHP?

When making HTTP requests in PHP, it is important to set a user-agent header to identify your request to the server. This header helps servers determine the type of client making the request and can prevent your request from being blocked or rejected. It is recommended to use a standard user-agent string that identifies your application or script.

$url = 'https://example.com/api';
$userAgent = 'MyApp/1.0'; // Set a custom user-agent string

$options = [
    'http' => [
        'header' => "User-Agent: $userAgent\r\n"
    ]
];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

echo $response;