What best practices should be followed when handling image URLs in PHP to ensure proper display?

When handling image URLs in PHP, it is important to properly sanitize and validate the URL to prevent any security vulnerabilities or errors. One best practice is to use the built-in filter_var() function with the FILTER_VALIDATE_URL filter to validate the URL. Additionally, it's recommended to use the htmlspecialchars() function to escape any special characters in the URL to prevent XSS attacks.

// Example of handling image URLs in PHP
$imageUrl = $_GET['image_url']; // Assuming the image URL is passed as a query parameter

// Validate the image URL
if (filter_var($imageUrl, FILTER_VALIDATE_URL)) {
    // Display the image using the sanitized URL
    echo '<img src="' . htmlspecialchars($imageUrl) . '" alt="Image">';
} else {
    // Handle invalid image URL
    echo 'Invalid image URL';
}