How can the use of user-agent headers impact the success of HTTP requests made in PHP?

When making HTTP requests in PHP, the use of user-agent headers can impact the success of the requests as some servers may require a specific user-agent to be set in order to respond correctly. To ensure the requests are successful, you can set a custom user-agent header in your PHP code to mimic a web browser or any other client that the server expects.

<?php

$url = 'https://example.com/api';
$userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3';

$options = array(
    'http' => array(
        'header'  => "User-Agent: $userAgent\r\n"
    )
);

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

echo $response;

?>