What are the best practices for handling images from a different server in PHP?

When handling images from a different server in PHP, it's important to ensure that the images are properly validated and sanitized to prevent security risks such as injection attacks. One common approach is to download the image from the remote server using functions like file_get_contents() and then outputting it using appropriate headers. Additionally, caching the images locally can help improve performance and reduce the load on the remote server.

<?php
// URL of the remote image
$remote_image_url = 'https://example.com/image.jpg';

// Download the image from the remote server
$image_data = file_get_contents($remote_image_url);

// Output appropriate headers for image display
header('Content-Type: image/jpeg');
echo $image_data;