What are the best practices for handling HTTP headers when accessing images from external sources in PHP?
When accessing images from external sources in PHP, it is important to properly handle HTTP headers to ensure the image is displayed correctly. One common issue is not setting the correct content-type header when outputting the image, which can result in the image not being displayed properly. To solve this, you can use the get_headers() function to retrieve the content-type header from the external image URL and then set the same header when outputting the image.
<?php
$image_url = 'https://example.com/image.jpg';
$headers = get_headers($image_url, 1);
$content_type = $headers['Content-Type'];
header('Content-Type: ' . $content_type);
readfile($image_url);