What potential security risks should be considered when dynamically loading images with PHP?

When dynamically loading images with PHP, one potential security risk to consider is the possibility of remote code execution if the image URL is not properly sanitized. To mitigate this risk, it is important to validate and sanitize the image URL before using it in the code. This can be done by checking if the URL starts with "http://" or "https://" and only allowing URLs from trusted sources.

$image_url = $_GET['image_url'];

if (filter_var($image_url, FILTER_VALIDATE_URL) && (strpos($image_url, 'http://') === 0 || strpos($image_url, 'https://') === 0)) {
    // Load the image using the validated URL
    echo '<img src="' . $image_url . '" alt="Image">';
} else {
    // Handle invalid image URL
    echo 'Invalid image URL';
}