How can PHP be used to prevent following redirects when using file_get_contents()?

When using file_get_contents() in PHP to fetch a URL, the function will automatically follow any redirects that the URL may have. To prevent following redirects, you can use the stream_context_create() function to create a context with the 'max_redirects' option set to 0.

$url = 'http://example.com';
$options = array(
    'http' => array(
        'max_redirects' => 0,
        'ignore_errors' => true
    )
);
$context = stream_context_create($options);
$data = file_get_contents($url, false, $context);
echo $data;