How can the use of User-Agent headers in PHP scripts impact the retrieval of data from external websites?

When making requests to external websites in PHP scripts, the User-Agent header identifies the client making the request. Some websites may block requests without a valid User-Agent header, leading to data retrieval issues. To ensure successful data retrieval, it's important to set a valid User-Agent header in your PHP script.

<?php
$url = 'https://example.com/data';
$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);
$data = file_get_contents($url, false, $context);

echo $data;
?>